c# - 将 byte[] 从 c# 传递到纯 c dll 时发生访问冲突

标签 c# c dll unity-game-engine access-violation

我正在尝试将 SOIL 库用于我的 Unity3d 项目。我稍微修改了代码,将其编译为 DLL。 我有一个带签名的 C 函数:

__declspec(dllexport)
unsigned int SOIL_load_OGL_texture_from_memory
    (
        const unsigned char *const buffer,
        int buffer_length,
        int force_channels,
        unsigned int reuse_texture_ID,
        unsigned int flags
    );

我在我的 C# 脚本中声明了它:

  [DllImport("SOIL", CallingConvention = CallingConvention.Cdecl)]
  private static extern uint SOIL_load_OGL_texture_from_memory(
    System.IntPtr buffer,
    int buffer_length,
    int force_channels,
    uint reuse_texture_ID,
    uint flags);

尝试调用:

GCHandle pinnedArray = GCHandle.Alloc(bytes, GCHandleType.Pinned);
System.IntPtr pointer = pinnedArray.AddrOfPinnedObject();
uint id = SOIL_load_OGL_texture_from_memory(pointer, bytes.Length, 3, 0, 0);
pinnedArray.Free();

并出现访问冲突。所以我尝试将 IntPtr 作为 const unsigned char * 传递。也许我需要使用与 GCHandle 不同的东西?

编辑:它在播放模式下使整个 Unity 3D 崩溃:MSVCR120.dll 处的访问冲突。

最佳答案

尝试Marshal.Copy(Byte[], Int32, IntPtr, Int32)并将指针传递给您的 C 调用

关于c# - 将 byte[] 从 c# 传递到纯 c dll 时发生访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25485496/

相关文章:

c# - EF 6 数据库第一个存储过程

c# - 添加通知图标后应用程序将不会在启动时启动

C 尝试添加撇号

c - 内联汇编器系统调用 PTRACE(不允许操作)

c++ - 尝试链接 dll 时出现错误 LNK2019 无法解析的外部符号

C++:检索共享库列表的跨平台方式

c# - 无法更改关系,因为一个或多个外键属性不可为空

c# - 关闭一个表单然后调用另一个

c - loader 和 C 运行时初始化的作用区别

c# - 在 .Net 2.0 的 64 位应用程序中使用 32 位 DLL