简体   繁体   中英

Passing a pointer of C# structure to C++ API

This is my structure and function in C++ dll

struct Address
{
    TCHAR* szAddress;
};

extern "C" DllExport void SetAddress(Address* addr);

From C# I want to call this API by passing the address structure. So, I have the following in C#

[StructLayout(LayoutKind.Sequential)] 
public struct Address
{
    [MarshalAs(UnmanagedType.LPTStr)]
    public String addressName;
}

[DllImport("Sample.dll")]
extern static void SetAddress(IntPtr addr);

Now, this is how I am calling the C++ API from C#

Address addr = new Address();
addr.addressName = "Some Address";
IntPtr pAddr = Marshal.AllocHGlobal(Marshal.SizeOf(addr));
Marshal.StructureToPtr(addr , pAddr , false);
SetAddress(pAddr); //CALLING HERE

I am getting NULL for Address.szAddress in C++ code. Any idea what is going wrong here ?

You can simply pass the Address struct by ref . You will also need to ensure that the calling conventions match. It looks to me as though the native code is cdecl . Finally, UnmanagedType.LPTStr means ANSI on Win9x and Unicode elsewhere. So, that is appropriate if the native code expects a UTF-16 string. If it expects ANSI then use UnmanagedType.LPStr instead.

This code works correctly, and the string specified in the C# code is received by the native code.

[StructLayout(LayoutKind.Sequential)]
public struct Address
{
    [MarshalAs(UnmanagedType.LPTStr)]
    public string addressName;
}

[DllImport(@"test.dll", CallingConvention=CallingConvention.Cdecl)]
extern static void SetAddress(ref Address addr);

static void Main(string[] args)
{
    Address addr;
    addr.addressName = "boo";
    SetAddress(ref addr);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM