简体   繁体   English

元帅 C++ int 数组到 C#

[英]Marshal C++ int array to C#

I would like to marshal an array of ints from C++ to C#.我想将一个整数数组从 C++ 编组到 C#。 I have an unmanaged C++ dll which contains:我有一个非托管的 C++ dll,其中包含:

DLL_EXPORT int* fnwrapper_intarr()
{
    int* test = new int[3];

    test[0] = 1;
    test[1] = 2;
    test[2] = 3;

    return test;
}

with declaration in header extern "C" DLL_EXPORT int* fnwrapper_intarr();在头文件extern "C" DLL_EXPORT int* fnwrapper_intarr();声明extern "C" DLL_EXPORT int* fnwrapper_intarr();

I am then using pinvoke to marshal it into C#:然后我使用 pinvoke 将其编组到 C# 中:

[DllImport("wrapper_demo_d.dll")]
[return: MarshalAs(UnmanagedType.SafeArray)]
public static extern int[] fnwrapper_intarr();

And I use the function like so:我像这样使用这个函数:

int[] test = fnwrapper_intarr();

However, during program execution I get the following error: SafeArray cannot be marshaled to this array type because it has either nonzero lower bounds or more than one dimension.但是,在程序执行期间,我收到以下错误: SafeArray cannot be marshaled to this array type because it has either nonzero lower bounds or more than one dimension.

What array type should I be using?我应该使用什么数组类型? Or is there a bettery way of marshalling arrays or vectors of integers?或者是否有更好的方法来编组数组或整数向量?

[DllImport("wrapper_demo_d.dll")]
public static extern IntPtr fnwrapper_intarr();

IntPtr ptr = fnwrapper_intarr();
int[] result = new int[3];
Marshal.Copy(ptr, result, 0, 3);

You need also to write Release function in unmanaged Dll, which deletes pointer created by fnwrapper_intarr.您还需要在非托管 Dll 中编写 Release 函数,该函数删除由 fnwrapper_intarr 创建的指针。 This function must accept IntPtr as parameter.此函数必须接受 IntPtr 作为参数。

DLL_EXPORT void fnwrapper_release(int* pArray)
{
    delete[] pArray;
}

[DllImport("wrapper_demo_d.dll")]
public static extern void fnwrapper_release(IntPtr ptr);

IntPtr ptr = fnwrapper_intarr();
...
fnwrapper_release(ptr);

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

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