Pinvoke-使用指针指向指针参数的指针来调用函数 [英] Pinvoke- to call a function with pointer to pointer to pointer parameter

查看:125
本文介绍了Pinvoke-使用指针指向指针参数的指针来调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C函数中具有以下签名:

I have a function in C with this signature:

int addPos(int init_array_size, 
           int *cnt, 
           int *array_size, 
           PosT ***posArray, 
           char *infoMsg);

这是PosT的样子:

typedef union pu
{
    struct  dpos   d;
    struct  epo    e;
    struct  bpos   b;
    struct  spos   c;
} PosT ;

通过P/Invoke在C#中调用此方法的最佳方法是什么?我是否需要在C#中定义一个表示PosT的类?如何将PosT *** posArray参数从C#传递到C?

What's the best way to call this method in C# via P/Invoke? Do I need to define a class in C# representing PosT? How do I pass PosT ***posArray parameter across from C# to C?

推荐答案

您已经描述了PosT的外观,但这还不够.首先,必须知道函数期望作为*** PosT参数传递的内容,只有THEN才可以考虑从C ++或C#端调用它.

You have described how the PosT looks like, but this is not enough. First, have to know what the function expects to be passed as the ***PosT argument, and only THEN you can think of invoking it from C++ or C# side.

我知道这可能不符合您的意愿,但是请注意:

I know that probably does not fit your wishes, but please look:

PosT p;
PosT* ptr = &p;
PosT** ptr2 = &ptr;
PosT*** ptr3 = &ptr2;
func(...., ptr3, ...); // OK!?


PosT* ptr = new PosT[123];
PosT** ptr2 = &ptr;
PosT*** ptr3 = &ptr2;
func(...., ptr3, ...); // OK!?


PosT** ptr2 = new PosT[5];
for(int i=0;i<5;++i) ptr2[i] = new PosT[123];
PosT*** ptr3 = &ptr2;
func(...., ptr3, ...); // OK!??

以此类推.我快速构建的哪种内存结构适合该功能?这就是确定必须从C#端传递的数据类型.

And so on. Which one in-memory structure that I have quickly built is correct for that function? This is what determines the datatype that you will have to pass from the C# side.

如果函数需要处理某事,您将称其为锯齿状的可变引用"(因此我提供了LAST示例),因此P/Invoke声明为:

If the function takes a thing you'd call a "mutable reference to jagged aray" (so the LAST example I provided), so the P/Invoke declaration would be:

[..extern..]
void func(....., ref PosT[][] posArray, ...);

调用类似于:

func(...., new PosT[][] { 
         new PosT[] { new PosT{ d = ... }, new PosT{ d = ... }, ... },
         new PosT[] { new PosT{ d = ... }, new PosT{ d = ... }, ... },
         ... },
    .... );

但是,请首先检查此功能的期望值.使用 * 的可能性真的太多了,无法猜测.您说它来自某个API-请先检查其文档!告诉我们此功能的确切含义,我/某人将告诉您如何在C#中构建此类POD.否则,它将无法正常工作! :)

but, please, first check what this function expects. With * there are really too many posibilities to just guess. You say it is from some API - check in its docs first! Tell us what exactly this function expects and me/someone will tell you how to build such POD in C#. Other way round it will not work! :)

PS.对于糟糕的C ++/C#代码感到抱歉,我匆忙忙忙,只有几分钟的时间来编写此代码:/

PS. sorry for crappy C++/C# code, I'm in haste and only had a few minutes to write this:/

这篇关于Pinvoke-使用指针指向指针参数的指针来调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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