gpt4 book ai didi

c# - 遍历从 C# 传递的未知 C 结构

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:43:45 26 4
gpt4 key购买 nike

我正在开发一个应从 C# 程序访问的 c .dll。理想情况下,.dll 应该接收在 C# 中定义的任何结构并对其执行某些操作。因此,最初,C dll 的结构类型和大小是未知的。我能够通过 C extern 函数传递该结构,并且它应该可以正常接收,但是,有没有办法找出这个接收结构的大小和特征?有没有办法遍历其成员?

这是为dll定义的C函数

extern int __cdecl testCSharp(mystruct * Test){

//sizeof(Test) is 4, so it is ok

for(int i=0;i < sizeof(Test) ; i++){

char * value = (char*) Test; //This access the first element.
cout << value << endl; //Prints "some random string", so, it is received ok
}

return 1;

这是C#代码

 [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]
unsafe public struct myStruct{
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 100)]
public string value1;
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 100)]
public string value2;
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 100)]
public string value3;
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 100)]
public string value4;
};

[DllImport("SMKcomUploadDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int testCSharp(ref myStruct message);

static void Main()
{
int result;

myStruct message = new myStruct();

message.value1 = "Some randome string";
message.value2 = "0";
message.value3 = "olkujhikvb";
message.value4 = "isabedfbfmlk";

result = testCSharp(ref message);
}

在 C# 中,所有类型都是字符串,并且应该保持这种状态,所以这是我对要传递的结构的唯一了解。

有什么想法吗?

提前致谢

最佳答案

当您将它们编码为长度为 100 的 ByValTStr 时,我不确定您是否能够比现有的(即第一个元素)更多地工作。

来自 MSDN ( here )

.NET Framework ByValTStr types behave like C-style, fixed-size strings inside a structure (for example, char s[5])

如果您改用 LPStr 或 LPWStr 空终止符,您将能够算出它们的长度。

关于c# - 遍历从 C# 传递的未知 C 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18016038/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com