c# - 为什么在 c#/c++ dll 互操作期间出现 System.AccessViolationException?

标签 c# c++ interop

<分区>

我是 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# 互操作期间处理内存管理的更多信息?

最佳答案

使用一个字符串试试这个:

private static extern void test(ref string text);

如果您想在测试函数中更改字符串,请使用 ref。否则你可以离开它。

关于c# - 为什么在 c#/c++ dll 互操作期间出现 System.AccessViolationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9191110/

相关文章:

c# - System.Text.Json JsonElement.GetProperty() KeyNotFoundException 异常

c++ - 强制页面边界段错误?

C++编译时检查模板类型中是否存在方法

c# - 如何将 wchar_t* 从 C++ 编码到 C# 作为输出参数或返回值?

c# - ASP.NET MVC 需要两个不同版本的 Newtonsoft.Json.dll

c# - 为什么将字符串路径转换为 ​​Geometry 并再次返回会抛出 FormatException?

c# - VS 2015 中的类库 - 构建跨平台库

c++ - 如何重载 += 运算符以返回字符串?

c# - 通过 C# Interop 执行 VBA 宏?

c# - 使用 C# 格式化 Excel 文件