对从c#传递的未知c结构进行迭代
iterate over unknown c struct passed from c#
我正在开发一个应该从c#程序访问的c.dll。理想情况下,.dll应该接收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#中的String,并且假设它保持原样,所以它是我对将要传递的结构唯一了解的内容。
知道吗?
提前感谢
当您将它们编组为长度为100的ByValTStr时,我不确定您是否能够处理比现有元素(即第一个元素)更多的内容。
来自MSDN(此处)
.NET Framework ByValTStr类型的行为类似于C样式、固定大小的字符串在结构内部(例如,char s[5])
如果使用LPStr或LPWStr null终止,则可以计算出它们的长度。
相关文章:
- C++结构编译器错误询问向量的迭代器
- 如何使用迭代器指向结构体c++的向量
- 在VS 2017中,朋友通过具有私有析构函数的结构的unique_ptr向量进行迭代失败
- 迭代结构中包含的向量
- 为结构的向量创建C 矢量迭代器
- 是否有一个很好的方法可以在C 11中打印出像JSON一样的Trie结构(仅迭代解决方案)的扁平命名空间
- 有没有办法迭代不完整的结构
- 用于隐藏结构细节的迭代器适配器
- 在 stl 中迭代结构类型的队列
- 无法迭代结构"string"的哈希映射:[列表] C++
- Boost Intervocess:通过迭代通过从结构引用对象的映射进行迭代时
- 如何从数据结构的向量中收集迭代器
- 当迭代器添加到添加到列表向量的结构时,迭代器停止指向值?
- 使用POCO迭代JSON结构
- 是否值得两次通过文件进行迭代,以创建最小的数据结构
- 创建自定义迭代器结构以与CSTDIO一起使用
- 在编译时使用模板在跨结构字段中迭代
- 正在取消引用自定义结构字段的迭代器
- 使用C预处理器在结构字段上进行迭代
- 如何列出向量中存储的结构迭代次数