bgura
bgura

Reputation: 869

Loading Unmanaged C++ in C#. Error Attempted to read or write protected memory

I have a C++ function that looks like this

    __declspec(dllexport) int ___stdcall RegisterPerson(char const * const szName)
    {
        std::string copyName( szName );
        // Assign name to a google protocol buffer object
        // Psuedo code follows..
        Protobuf::Person person;
        person.set_name(copyName);
        // Error Occurs here...
        std::cerr << person->DebugString() << std::endl;
    }

The corresponding C# code looks like this...

    [DllImport(@"MyLibrary.dll", SetLastError = true)]
    public static unsafe extern int RegisterPerson([MarshalAs(UnmanagedType.LPTStr)]string szName)

Not sure why this is not working. My C++ library is compiled as Multi Threaded DLL with MultiByte encoding.

Any help would be appreciated. I saw this is a common problem online but no answers lead me to a solution for my problem.

I was able to successfully call another exported function with the same function parameters that my DLL exports and that one worked fine. This "register person" function is a bit longer than that other exported function though and for some reason does not work.

Upvotes: 0

Views: 452

Answers (1)

Matt
Matt

Reputation: 6050

First, the define of C++ functions miss the extern "C", if not specified, the Pinvoke can't find the function because of C++ name mingling.

As the define in C#, you specify UnmanagedType.LPTStr, by default, it will be wide char, but the parameter in C++ function RegisterPerson is char, you should change it to UnmanagedType.LPStr.

More details can be found in the MSDN library.

Upvotes: 1

Related Questions