Passing a pointer to a C # structure in 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 name this API by passing an 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 I call 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 get NULL for Address.szAddress in C ++ code. Any idea what is going wrong here?

+4
source share
1 answer

You can simply pass the Address structure to ref . You also need to make sure that the calling conventions match. It seems to me that native code is cdecl . Finally, UnmanagedType.LPTStr means ANSI on Win9x and Unicode elsewhere. Thus, this is suitable if native code expects a UTF-16 string. If it expects ANSI, use UnmanagedType.LPStr .

This code works correctly, and the line specified in the C # code is accepted using its own 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); } 
+6
source

Source: https://habr.com/ru/post/1485532/


All Articles