Using a DLL in C#

  • Thread starter Thread starter Stephen Holly
  • Start date Start date
S

Stephen Holly

Hi All,

I have some source code writen in c that implements the blowfish encryption
algorithm which I have created as a DLL and want to use it in a .NET
solution.

I want to pass some params and get the encrypted string from it. I have
managed (as a test) to get my dll to return an integer and for the .NET to
accept it, however when I try to get the dll to return a char*, it fails due
to.....

ERROR{
An unhandled exception of type
'System.Runtime.InteropServices.MarshalDirectiveException' occurred in
ConsoleApplication1.exe
Additional information: Can not marshal return value.
}

I have tried reading about managed and unmanaged code and about marshalling
but do not understand it enough to solve the problem.

The relevent code snips are below.

Can anyone help? :)

--Steve

C{
__declspec( dllexport ) char* BF_cbc_encrypt()

unsigned char *out;
........................
.......................
return out;
}

C#{
.............................
[DllImport("libeay32.dll")]
public static extern char[] BF_cbc_encrypt();
...............................
...............................
char[] ret = BF_cbc_encrypt();
System.Console.WriteLine(ret);
}
 
Hi, Stephen
Normally you can use string to marshal char * return value. But maybe
what you want is a byte array not char array(unicode) reprentation, in such
case, you can use System.IntPtr to get the pointer, then use Marshal.Copy to
copy into a byte array. If you use Ptr, you can do more controls like
freeing the memory allocated by GlobalAlloc in native side.

[DllImport("libeay32.dll")]
public static extern string BF_cbc_encrypt();

or

[DllImport("libeay32.dll")]
public static extern System.IntPtr BF_cbc_encrypt();


Hope it helps!

Qiu
 
Back
Top