这是我在C++ dll中的结构和函数
struct Address
{
TCHAR* szAddress;
};
extern "C" DllExport void SetAddress(Address* addr);
在 C# 中,我想通过传递地址结构来调用此 API。所以,我在 C# 中有以下内容
[StructLayout(LayoutKind.Sequential)]
public struct Address
{
[MarshalAs(UnmanagedType.LPTStr)]
public String addressName;
}
[DllImport("Sample.dll")]
extern static void SetAddress(IntPtr addr);
现在,这就是我从 C# 调用 C++ API 的方式
Address addr = new Address();
addr.addressName = "Some Address";
IntPtr pAddr = Marshal.AllocHGlobal(Marshal.SizeOf(addr));
Marshal.StructureToPtr(addr , pAddr , false);
SetAddress(pAddr); //CALLING HERE
我在 C++ 代码中得到的 Address.szAddress 为 NULL。知道这里出了什么问题吗?
最佳答案
您可以通过 ref
简单地传递 Address
结构。您还需要确保调用约定匹配。在我看来, native 代码似乎是 cdecl
。最后,UnmanagedType.LPTStr
在 Win9x 上表示 ANSI,在其他地方表示 Unicode。因此,如果 native 代码需要 UTF-16 字符串,这是合适的。如果它需要 ANSI,则使用 UnmanagedType.LPStr
。
此代码工作正常, native 代码接收 C# 代码中指定的字符串。
[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);
}
关于c# - 将 C# 结构的指针传递给 C++ API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17034728/