【发布时间】:2012-02-08 10:02:45
【问题描述】:
我是 C# 和 .NET 的新手。我想在 .NET 中使用我现有的 C++ dll,所以我正在尝试互操作。我不知道为什么会引发此异常。我知道这个异常意味着什么,我阅读了 MSDN,但不确定为什么会出现这种情况。
我的代码是这样的。
dll 代码是一个简单的函数,它采用char*。
extern "C" __declspec(dllexport)void test(char *text)
{
// these raise System.AccessViolationException
// char c = text[0];
// int n = strlen(text);
// char *copy = strdup(text);
}
C#代码是一个调用这个函数的简单类
namespace Interop_test
{
class Program
{
static void Main(string[] args)
{
char[] text = new char[10];
for (int i = 0; i < 10; i++)
text[i] = (char)('A' + i);
test(text);
}
[DllImport("interop_test_dll.dll")]
private static extern void test(char[] text);
}
}
如果删除 dll 函数中注释掉的代码,则会引发上述异常。为什么?
我如何(或必须)将一组数据从 C# 传递到 C++?
在哪里可以找到有关在 C++/C# 互操作期间处理内存管理的更多信息?
【问题讨论】: