繁体   English   中英

如何将struct中的char *从c#传递给c ++

[英]How to pass char* in struct from c# to c++

感觉就像我的问题类似于

到目前为止,我有一个在C ++中定义的结构,如下所示:

typedef struct struct_type1
{
    uint64  nameLen;
    char *  name;  
} STATUSSTRUCT;

和一个定义为的函数:

extern int _stdcall getStatus(STATUSSTRUCT * status);

并且可能是这样的功能:

int _stdcall getStatus(STATUSSTRUCT * status)
{
    status->nameLen = someLength;
    status->name = someName;
    return 1;
}

请注意,我实际上无法更改C ++代码(出于各种原因)或头文件。

我的C#代码如下所示:

public struct STATUSSTRUCT
{
    public UInt64 nameLen;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4128)]
    public byte[] name;
}
STATUSSTRUCT status;

[DllImport("test.dll", CallingConvention = CallingConvention.StdCall)]
public static extern int getStatus(ref STATUSSTRUCT status);

public void refreshStatus() {
    status = new STATUSSTRUCT();
    status.nameLen = 4128;
    status.name = new byte[4128];
    getStatus(ref status);
}

但是,调用refreshStatus会给我System.AccessViolationException。

有人可以帮我弄清楚如何用C#在C ++中调用这个函数吗?

您的结构需要一个指向数组的指针 ; 你正在编组阵列 该交易的一方希望获得“123芝麻街”的地址,并且您正在该地址提供公寓大楼的精确复制品。 那不行。

要使编组代码正确,您需要对C#中的内存管理有一个全面而深入的了解 我的建议是你获得专家的服务。

您可以尝试使用StringBuilder而不是byte []和LPStr而不是ByValArray:

public struct STATUSSTRUCT
{
    public UInt64 nameLen;
    [MarshalAs(UnmanagedType.LPStr, SizeConst = 4128)]
    public StringBuilder name;
}

status = new STATUSSTRUCT();
status.nameLen = 4128;
status.name = new StringBuilder(4128);
getStatus(ref status);

https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.unmanagedtype(v=vs.110).aspx

暂无
暂无

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

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