【问题标题】:Marshal.Copy not copying over valueMarshal.Copy 不复制价值
【发布时间】:2018-10-30 18:47:16
【问题描述】:

我对 C# 不是很熟悉,我正在尝试使用 'Marshal.Copy',但这并没有改变我正在使用的 IntPtr 的值。

IntPtr ptr = InitPointer(width, height);

Marshal.Copy(inputIntArray, 0, ptr, width * height * 4);

其中 InitPointer 定义为:

[DllImport(@"../../../../Debug/KernelApplier.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr InitPointer(int x, int y);

在我的 kerneApplier.dll 中,函数写为:

int * inputBuffer;
int size;
int m_x, m_y;

extern "C" __declspec(dllexport) int* InitPointer(int x, int y) {
    size = x*y * sizeof(cl_int3);
    m_x = x;
    m_y = y;
    inputBuffer = (int*)malloc(size * sizeof(int));
    return inputBuffer;
}

我正在使用我的监视窗口来监视以下值:

  • ptr.m_value = 0x0641c040
  • inputIntArray[0] = 152
  • 0x0641c040 = 104972352 //这在 Marshal.Copy 之后没有变化

我是在错误地使用 Marshal.copy 还是将数据从 C++ 传递到 C# 时出现问题

【问题讨论】:

  • 你注意到1049723520x641C040 了吗?您不能在监视窗口中输入数字,因为它永远只是一个数字
  • 当您说“将数据从 C++ 复制到 C#”时会让人感到困惑。是的,指针在 C++ 代码中分配并传递给 C# 代码。但是数组中的数据正在从 C# 传递到 C++。至少这就是我认为正在发生的事情.....
  • 你不是在改变指针,而是在改变它指向的内存。使用 Debug > Windows > Memory > Memory1 并将“ptr”放在地址框中,现在您可以看到它。
  • 大卫,谢谢,我会澄清我的问题。 Hans & Thomas,感谢您告诉我如何查看指针中存储的内容。

标签: c# marshalling dllimport intptr


【解决方案1】:

您的代码很好。 IntPtr 值不会改变,但它是非托管内存的地址,因此预计不会改变。

【讨论】:

    猜你喜欢
    • 2015-01-25
    • 2015-02-07
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多