Search code examples
c#c++pinvoke

Attempting to read/write protected memory error while pinvoking a c++ function


I have a C++ project X with calling convention set as __stdcall (/Gz) and a C# project Y.

I have defined a class myClass in BOTH these projects.

class myClass
{
    private:int mem1;
};

In the C# definition of the class, I have prefixed it with

[StructLayout(LayoutKind.Sequential)]

The C++ function is

 _declspec (dllexport) void getLen(myClass* str)
 {
     printf("%s",sizeof(int));
 }

In Y, I have defined the function as follows

[DllImport("X.dll")]
private static extern void getLen(ref myClass str);

And I am calling it like this:

getLen(ref str);

where str is an object of type myClass.

Why is this error coming up when I run this solution?


Solution

  • Your problem is in the printf() call: "%s" expects a pointer to a null-terminated string of characters, but you are providing a size_t.