简体   繁体   English

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

[英]Passing a pointer of C# structure to C++ API

This is my structure and function in C++ dll 这是我在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. 从C#中,我想通过传递地址结构来调用此API。 So, I have the following in C# 所以,我在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# 现在,这就是我从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

I am getting NULL for Address.szAddress in C++ code. 我在C ++代码中获取Address.szAddress的NULL。 Any idea what is going wrong here ? 知道这里出了什么问题吗?

You can simply pass the Address struct by ref . 您可以简单地通过ref传递Address结构。 You will also need to ensure that the calling conventions match. 您还需要确保调用约定匹配。 It looks to me as though the native code is cdecl . 在我看来,本机代码是cdecl Finally, UnmanagedType.LPTStr means ANSI on Win9x and Unicode elsewhere. 最后, UnmanagedType.LPTStr表示Win9x上的ANSI和其他地方的Unicode。 So, that is appropriate if the native code expects a UTF-16 string. 因此,如果本机代码需要UTF-16字符串,则这是适当的。 If it expects ANSI then use UnmanagedType.LPStr instead. 如果期望使用ANSI,则改用UnmanagedType.LPStr

This code works correctly, and the string specified in the C# code is received by the native code. 该代码可以正常工作,并且本机代码会接收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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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