【发布时间】:2015-03-13 22:51:06
【问题描述】:
所以我试图从一些 c# 代码在 dll 中运行 c++ 本机函数。它工作正常,但是,当我在函数调用中使用“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 设置为任何内容,我就会收到以下错误:
Assembly-CSharp.DLL 中出现“System.AccessViolationException”类型的异常,但未在用户代码中处理 附加信息:试图读取或写入受保护的内存。这通常表明其他内存已损坏。
【问题讨论】:
-
您还必须添加 P/Invoke 定义(
[DllImport]等)。 -
对不起,我忘了显示那个定义。现在编辑问题。
-
可能重复:stackoverflow.com/questions/26992178/c-sharp-dllimport-with-pointers
-
我不认为这是重复的。我认为那个问题或答案对我没有帮助。
-
这是您的 C++ 代码最有可能发生爆炸的方式,因为 [DllImport] 声明与 C++ 函数不匹配。 不是最后一个参数是问题所在,而是其他参数。关于他们所有人。 非常怀疑你是否可以使用 pinvoke 来完成这项工作,请改用 C++/CLI。