相关疑难解决方法(0)

P/Invoke [In,Out]属性是否可选用于编组数组?

假设存在一个带有纯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++ arrays pinvoke attributes

11
推荐指数
1
解决办法
4263
查看次数

从C++本机插件更新float数组

在尝试将数组从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)

c# c++ interop unity-game-engine

1
推荐指数
1
解决办法
2010
查看次数

标签 统计

c# ×2

c++ ×2

arrays ×1

attributes ×1

interop ×1

pinvoke ×1

unity-game-engine ×1