PInvoke的:问题与双打返回数组? [英] PInvoke: Issue with returned array of doubles?

查看:119
本文介绍了PInvoke的:问题与双打返回数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的PInvoke 来调用从我的C#程序中的C ++函数。代码如下:

I am using PInvoke to call a C++ function from my C# program. The code looks like this:

IntPtr data = Poll(this.vhtHand);
double[] arr = new double[NR_FINGERS /* = 5 */ * NR_JOINTS /* = 3*/];
Marshal.Copy(data, arr, 0, arr.Length);

通过民意测验()的签名期待像这样的:

With Poll()'s signature looking like this:

[DllImport("VirtualHandBridge.dll")]
static public extern IntPtr Poll(IntPtr hand);



的C函数民意测验的签名

extern "C" __declspec(dllexport) double* Poll(CyberHand::Hand* hand)

除非我有一个巨大的脑功能衰竭(诚然,相当普遍的对我来说),这看起来对我来说,应该是工作

Unless I'm having a huge brain failure (admittedly, fairly common for me), this looks to me like it should be working.

不过,我得到双重价值是完全不正确的,我想这是因为不正确的内存使用量。我也看着它,我想在C#和C ++双打的大小是相同的,但也许有一些其他的问题,在这里打球。这有点让我反感这样的一件事是 Marshal.Copy 从未告知它应该期待什么类型的数据,但我读了它应该这样使用。

However, the double values I am getting are completely incorrect, and I think this is because of incorrect memory usage. I have looked it up, and I think doubles in C# and C++ are identical in size, but maybe there is some other issue playing here. One thing that rubs me the wrong way is that Marshal.Copy is never told what type of data it should expect, but I read that it is supposed to be used this way.

任何线索,任何人吗?如果需要,我可以张贴正确的结果,并返回结果。

Any clues, anyone? If needed, I can post the correct results and the returned results.

推荐答案

您缺少CallingConvention财产,这是CDECL。

You are missing the CallingConvention property, it is Cdecl.

您真的想要有利于更好的函数签名,你有一个是非常脆由于内存管理问题,需要手动封送处理,获得正确的不确定性尺寸数组和复制的数据的要求。总是青睐主叫方传递一个本地代码中填充的缓冲区:

You really want to favor a better function signature, the one you have is extremely brittle due to the memory management problem, the required manual marshaling, the uncertainty of getting the right size array and the requirement to copy the data. Always favor the caller passing a buffer that your native code fills in:

extern "C" __declspec(dllexport)
int __stdcall Poll(CyberHand::Hand* hand, double* buffer, size_t bufferSize)

[DllImport("foo.dll")]
private static extern int Poll(IntPtr hand, double[] buffer, int bufferSize)

使用整型返回值来报告的状态代码。像一个负值来报告错误代码,正值返回实际复制到缓冲元件的数目

Use the int return value to report a status code. Like a negative value to report an error code, a positive value to return the number of elements actually copied into the buffer.

这篇关于PInvoke的:问题与双打返回数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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