Access violation exception on the native side during interop

  access-violation, c++, interop

I have following code defined on the C# side that gets data from C++ library.

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct Address
{
    public string StreetName;
    public int StreetNumber;
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct Person
{
    public Address address;
}
    

[DllImport("MyLib", CharSet = CharSet.Unicode)]
internal static extern int GetPersonInfo(ref Person p);

In the native code, this method and required structs are defined as follows

typedef struct Address
{
    std::wstring StreetName;
    int StreetNumber;
} Address;

typedef struct Person
{
    Address address;
} Person;


extern "C" __declspec(dllexport) int GetPersonInfo( Person& p)
{
    Address address;
    address.StreetName = L"my address";
    address.StreetNumber = 87;
    p.address =address;
    return 0;
}

Then I have following code in c# to invoke the method

Person person= new Person();
var error = MyNativeCode.GetPersonInfo(ref person); 

I am getting a C++ access violation in the GetPersonInfo method at the following line.

p.address = address;

This works fine though if I comment out the string StreetName field from the Address class. It seems like I am doing something wrong during marshalling of string type but I don’t know what and how to fix it. TIA

Source: Windows Questions C++

LEAVE A COMMENT