我有一个带有以下签名的 C 函数:
int addPos(int init_array_size,
int *cnt,
int *array_size,
PosT ***posArray,
char *infoMsg);
这是 PostT 的样子:
typedef union pu
{
struct dpos d;
struct epo e;
struct bpos b;
struct spos c;
} PosT ;
在 C# 中通过 P/Invoke 调用此方法的最佳方式是什么?我需要在 C# 中定义一个代表 PosT 的类吗?如何将 PosT ***posArray 参数从 C# 传递到 C?
最佳答案
您已经描述了 PostT 的样子,但这还不够。首先,必须知道该函数期望作为 ***PosT 参数传递什么,然后您才能考虑从 C++ 或 C# 端调用它。
我知道这可能不符合您的意愿,但请看:
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# 端传递的数据类型。
如果函数接受一个你称之为“对锯齿状数组的可变引用”的东西(所以我提供的最后一个例子),那么 P/Invoke 声明将是:
[..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。反之则不行! :)
PS。抱歉,我的 C++/C# 代码很蹩脚,我很匆忙,只有几分钟的时间来写这个:/关于c# - Pinvoke-使用指向指针参数的指针来调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13957412/