从调用C ++ DLL的函数返回结构到C# [英] Returning a structure from a call to a C++ DLL's function to C#

查看:103
本文介绍了从调用C ++ DLL的函数返回结构到C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将结构从调用DLL返回到C#

这是我在C ++中的代码

Returning a structure from a call to a DLL to C#

Here is my code in C++

struct abc
{
    int a;
    int b[5]
};

struct abc mystruct()
{
    struct abc a1;
    a1.a=12;
    for(int i=0;i<5;i++)
        a1.b[i]=i*i;
    return a2;
}




我想在C ++中创建DLL后在C#Win32应用程序中调用此函数.我的C#结构是这样的:




I want to call this function in C# Win32 application after having created the DLL in C++. My C# structure is like this:

public struct abc
{
    public int a;
    public int []b;
};

[DllImport("C:\\mydll.dll")]
public static extern abc mystruct();

private void button5_Click(object sender, EventArgs e)
{
    abc a2=new bcd () ;
    a2.b = new int[5];
    a2 = mystruct(10);
}





每当我编译它时,都会出现以下错误:





Whenever I compile it it givse me this error:

"Method''s type signature is not PInvoke compatible."


谁能给我解决这个问题的方法.如果我从结构中删除数组,则编译成功.

在此先感谢!


Can anyone please provide me a solution to this problem. If I remove the array from the struct it compiles successfully.

Thanks in advance!

推荐答案


您必须提供数组的大小.
请尝试以下操作:

Hi,
you have to provide the size of the array.
Try the following:

public struct abc
{
    public int a;
    [System.Runtime.InteropServices.MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
    public int[] b;
}


您的编组错误.使用[System.Runtime.InteropServices.MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)] 将结构的b []字段编组起来或使用不安全的代码
public fixed int b[5].
顺便说一句,您的示例代码是错误的(bcd,a2.b = new int [5],mystruct(10)).请在发布之前进行测试...
Your marshalling is wrong. Marshal the b[] field of your struct with [System.Runtime.InteropServices.MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)] or use unsafe code
public fixed int b[5].
Btw your example code is wrong (bcd, a2.b = new int[5], mystruct(10)). Please test before posting...


这篇关于从调用C ++ DLL的函数返回结构到C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆