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

Posted by Thatoneguy on Stack Overflow See other posts from Stack Overflow or by Thatoneguy
Published on 2012-11-20T04:57:39Z Indexed on 2012/11/20 4:59 UTC
Read the original article Hit count: 145

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about c++

Related posts about visual-c++-2010