将结构中的数组作为参数从C ++/CLI传递到win32 dll [英] Pass an Array in a Struct as parameter from C++/CLI to win32 dll

查看:50
本文介绍了将结构中的数组作为参数从C ++/CLI传递到win32 dll的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我有一个封装在win 32 dll中的非托管C函数,该dll以结构作为参数,其中包含固定长度的数组.我已经在C和C ++/CLI中声明了数组,因此应隐式处理类型转换.

当我调试时,传递到非托管代码中的数组偏移16个字节(看似数组的标头信息).只要使用了偏移量,数据就可以返回到托管代码.

这是非托管结构的简化版本:

Hi All,

I have an unmanaged C function wrapped in a win 32 dll that takes in a struct as a parameter, that contains a fixed length array. I have declared the array in both C and C++/CLI so the type conversion should be handled implicitly.

When I debug, the array that is passed into the unmanaged code is offset by 16 bytes (seemingly the header information for the array). Data can be returned to the managed code so long as the offset is used.

Here is a cut down version of the unmanaged struct:

typedef struct test_struct{
    uint8_t Array[100];
} test_struct;



和相应的受管版本



and the corresponding managed version

[StructLayout(LayoutKind::Sequential)]
ref struct test_struct {
      [MarshalAs(UnmanagedType::ByValArray,SizeConst=100)]
      static array<unsigned char>^ Array;     
};



这是非托管函数的原型



This is the prototype for the unmanaged function

int function_test(test_struct * test)



以及来自托管代码的调用



and the call from managed code

int Test (test_struct^% pTest) {
            test_struct test;
            test.Array = gcnew array<unsigned char>(100);

            test.Array[0] = 2;

            int result = function_test (test);

            pTest = %test;
            return result;
        }



在通话时,结构指示:
数组[0] = 2
Array [1] = 0
Array [2] = 0


然后在通话中,争论变为
Array [0到15] =随机数据
数组[16] = 2
数组[17] = 0
数组[18] = 0


在此先谢谢您.



At the time of the call, the struct indicates:
Array[0] = 2
Array[1] = 0
Array[2] = 0
etc

Then inside the call the arguement changes to
Array[0 to 15] = Random data
Array[16] = 2
Array[17] = 0
Array[18] = 0
etc

Thanks in advance.

推荐答案

请尝试不要在托管定义中将数组设为静态.

我这样测试过...
Try NOT making the array static in the managed definition.

I tested like this...
[StructLayout(LayoutKind::Sequential)]  //, Pack=?
ref struct test_struct {
      [MarshalAs(UnmanagedType::ByValArray,SizeConst=100)]
      array<unsigned char>^ Array;  //static    
};

[DllImport("CPPLibraryTester.dll",CallingConvention=CallingConvention::Cdecl)]
extern "C" Int32 function_test([MarshalAs(UnmanagedType::LPStruct), In, Out] test_struct ^ts);


像这样的非托管代码...


with unmanaged code like this...

typedef struct test_struct{
    unsigned char Array[100];
} test_struct;


extern "C"
{

    __declspec( dllexport ) int function_test(test_struct * test)
    {
        return 0;
    }

}


这篇关于将结构中的数组作为参数从C ++/CLI传递到win32 dll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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