c# - 将 C# 结构的指针传递给 C++ API

标签 c# c++ interop pinvoke marshalling

这是我在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/

相关文章:

c# - 在 C# 中,如何调用返回包含字符串指针的非托管结构的 DLL 函数?

com - Outlook Interop 复制邮件项目

c# - 连接表,获取对象引用未设置

c# - 使用C#增大或减小音频文件的音高

c++ - 尝试将 const char * 转换为 NSString 时为空字符串

c++ - 是否可以将名称附加到 C++ 中的运行时类?

c++ - 将字符串存储为 char[] 并放置新的并将其取回

c# - 使用 LINQ 创建类似面包屑的层次结构

c# - protected 内部成员的可访问性不一致

ruby - 使用 Clojure 的 gem 中提供的 JRuby 类