Call Delphi DLL Function from C#

2019-08-08 19:51发布

this is the Delphi function header:

function CryptStr(str, Key : pchar; DecryptStr : boolean) : pchar; stdcall;


how to call this function from C#. it's actually inside a DLL named Crypto.dll

please guide
thanks

1条回答
倾城 Initia
2楼-- · 2019-08-08 20:04

Assuming that PChar is PAnsiChar:

[DllImport("Crypto.dll")]
static extern IntPtr CryptStr(string str, string Key, bool DecryptStr);

And then call it like this:

IntPtr retvalPtr = CryptStr(str, Key, DecryptStr);
string retval = Marshal.PtrToStringAnsi(retvalPtr);

And I expect you'll also need to call the function that the DLL exports that frees the memory behind the pointer that CryptStr returned. You did export such a function I trust?

If PChar is PWideChar then it would be:

[DllImport("Crypto.dll", CharSet = CharSet.Unicode)]
static extern IntPtr CryptStr(string str, string Key, bool DecryptStr);

And then call it like this:

IntPtr retvalPtr = CryptStr(str, Key, DecryptStr);
string retval = Marshal.PtrToStringUni(retvalPtr);

Finally, if you wanted to be really cute, you could arrange for the Delphi code to allocate the return value string from the COM heap using CoTaskMemAlloc. If you did that, then you could avoid the manual marshalling, and let the p/invoke marshaller perform the deallocation. That would look like this.

[DllImport("Crypto.dll", CharSet = CharSet.Unicode)]
static extern string CryptStr(string str, string Key, bool DecryptStr);

And then call it like this:

string retval = CryptStr(str, Key, DecryptStr);

It should be obvious now how to code the ANSI variant and so I will omit it.

When you declare a p/invoke with a string return value, the marshaller assumes that the native code returns a pointer to a null-terminated array of characters. And it also assumes that the memory was allocated off the COM heap, and makes a call to CoTaskMemFree to deallocate the memory. So, doing it this way avoids the need for a separate deallocator function to be exported from the DLL.

查看更多
登录 后发表回答