首页 > 解决方案 > 将 C# 中的 stringbuilder 或 byte[] 传递到非托管 API 兑现异常访问冲突

问题描述

我有一个非托管 API,其签名是:

int ImportFile( char *sFileName )

其中 Filename 是要导入的文件的名称、完整路径和文件名。

所以我在我的 C# 代码中使用这个 API:

string StepFilePath = @"C:\Users\pandey\AppData\Local\Temp\W-00004_CAD.stp";

StringBuilder Sb = new StringBuilder(256);

if (!String.IsNullOrEmpty(StepFilePath))
{
    Sb.Append(StepFilePath);
}

int a = API.ImportFile(Sb);

此时它崩溃并给出错误访问冲突读取位置错误。我什至尝试使用 byte[] 代替 stringbuilder 但它没有用。

我已经在一个单独的 API.cs 文件中声明了这个 API,如下所示:

[DllImport("exe name", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
unsafe extern static public int ImportFile(StringBuilder aStringBuilder);

任何想法可能是什么问题?我应该使用其他东西来代替 StringBuilder 还是 byte[]。

标签: c#

解决方案


推荐阅读