所以我正在尝试从某些 C# 代码在 dll 中运行 C++ native 函数。它工作正常,但是,当我在我的函数调用中使用“out”时,我遇到了内存访问冲突。这是它的样子:
C#函数
[DllImport(pluginName)]
public static extern IntPtr AddTriangleFixtuers(ShapeDef shapeDef, IntPtr toBody, ref Vector2 vertices, int triangleCount, Vector3 row1, Vector3 row2, out int fixtureCount);
...
int test = 1;
B2D.AddTriangleFixtuers(def, body.body, ref shapeTriangles[0], shapeTriangles.Length/3, firstRow, secondRow, out test);
C++函数
EXTERN_DLL_EXPORT b2Fixture* __stdcall AddTriangleFixtuers(ShapeDef shapeDef, IntPtr* toBody, b2Vec2* vertices, int triangleCount, b2Vec3 row1, b2Vec3 row2, int& fixtureCount) {
fixtureCount = 0;
b2Fixture* lastFixture = NULL;
return lastFixture;
}
我已将代码最小化以突出显示我遇到的问题。一旦我尝试将 C++ 代码中的 fixtureCount 设置为任何值,我就会收到以下错误:
An exception of type 'System.AccessViolationException' occurred in Assembly-CSharp.DLL but was not handled in user code Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
最佳答案
好吧,我终于明白了。导致内存访问冲突的是 row1 和 row2。即使我没有在我的 C++ 代码中使用它们。我必须将 x、y、z 值作为 float 发送以修复崩溃。
所以问题出在从 Vector3 到 b2Vec3 的转换上。就像汉斯在评论中提到的那样,问题不在于 fixtureCount。
关于c# - 使用out参数从c#调用 native c++代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27965227/