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

标签 c# c++ dll struct iteration

我正在开发一个应从 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/

相关文章:

c# - Discord C# Bot - 删除最新消息

c# - XAML 数据绑定(bind)在属性更改时不更新 UI

C# 将输入与mysql值进行比较

python - 如何修复导入错误: DLL load failed for scipy.空间模块?

来自 DLL 的 Delphi 接口(interface)

c# - asp.net mvc 5 自定义应用程序中的 Microsoft 登录问题

c++ - 处理通用代码中不一致的 typedef

python - filter2D OpenCV 函数 c++

java - 解析格式错误的 HTML 文档

c++ - Windows 库包含在 CMake 项目中