假设存在一个带有纯C接口的本机函数,如下所示,从本机DLL导出:
// NativeDll.cpp
extern "C" void __stdcall FillArray(
int fillValue,
int count,
int* data)
{
// Assume parameters are OK...
// Fill the array
for (int i = 0; i < count; i++)
{
data[i] = fillValue;
}
}
Run Code Online (Sandbox Code Playgroud)
以下P/Invoke工作正常(使用VS2010 SP1测试):
[DllImport("NativeDll.dll", CallingConvention=CallingConvention.StdCall)]
public static extern void FillArray(
int fillValue,
int count,
[In, Out] int[] data
);
Run Code Online (Sandbox Code Playgroud)
以及这个P /调用,与上面相同,但没有将[In, Out]
属性:
[DllImport("NativeDll.dll", CallingConvention=CallingConvention.StdCall)]
public static extern void FillArray(
int fillValue,
int count,
int[] data
);
Run Code Online (Sandbox Code Playgroud)
那么,这些 …
在尝试将数组从C++传递给C#时,我看到了一个非常奇怪的问题.我正在使用Marshal.Copy(具体来说:https://msdn.microsoft.com/en-us/library/a53bd6cz(v = vs1010 ).aspx ).
问题:从C++到C#的float数组NaN
在结果数组中产生了一些.
(注意:我在Unity游戏引擎的上下文中工作)
码
示例C++代码:
extern "C" bool UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API getSomeFloats(float** points, int* count) {
std::vector<float> results;
std::vector<SOME_TYPE> key_points = <SOME_POINTS>
for (auto iter = key_points.begin(); iter < key_points.end(); iter++) {
results.push_back(static_cast<float>(iter->pt.x));
results.push_back(static_cast<float>(iter->pt.y));
}
*points = results.data();
*count = results.size();
//<Print results to csv here>
return true;
}
Run Code Online (Sandbox Code Playgroud)
示例C#代码:
[DllImport("NativePlugin")]
private static extern bool getSomeFloats (ref IntPtr ptrResultItems, ref int resultItemsLength);
private static float[] getFloatArrayFromNative() {
IntPtr ptrResultItems = IntPtr.Zero;
int …
Run Code Online (Sandbox Code Playgroud)