Execute C++ function from C# application

240 views Asked by At

I have a DLL written in C++ which is a wrapper for C# around an LZO library. But for testing purposes I want to know if I can convert the types, so I created a test function that takes in the file's content and size and writes a copy of it.

extern "C" 
{
     __declspec(dllexport) void WriteFile(lzo_uint8 * source, int size)
    {
        FILE * fileToWrite;
       fileToWrite = fopen("test.eix", "wb+");
       if (fileToWrite)
       {
          fwrite(source, 1, size, fileToWrite);
       }
       fclose(fileToWrite);
       free(source);
    }
  }

Here is the image of the code, for better readability: http://i.epvpimg.com/u4mgh.png

I then import it like this:

[DllImport(@"GLZO.dll")]
public static extern void WriteFile(byte[] source, int size);

And call it like this:

        byte[] g = ReadFile("raw/roota.eix");
        WriteFile(g, g.Length);

The problem is not in the ReadFile function, I checked it. I created a copy from a different file and checked both with checksums.

So, my question is: how should I convert a byte[] to an lzo_uint8* (unsigned char*)?

1

There are 1 answers

0
Rodrigo Silva On BEST ANSWER

Got it! I just had to marshal it to an IntPtr, unsigned char * = IntPtr in C#.

Also, to avoid exceptions regarding "not equivalent" types, you need to import the dll as this:

        [DllImport(@"GLZO.dll", CallingConvention = CallingConvention.Cdecl)]