c# - 将 C++ 结构编码(marshal)至 C# 类时出现 AccessViolationException

标签 c# c++ struct pinvoke marshalling

我正在尝试使用 PInvoke 将 C++ 库 (libclang) 包装到 C# 包装器中。

一切都很 Shiny ,直到我尝试调用返回结构的 C++ 方法。 我做了一切by the book ,但是当调用此方法时,我收到 AccessViolationException。

现在,我读到这可能是因为对象的内存图像出现了问题。我检查并再次检查是否已将所有 Arrtibutes 和未放置在各处的内容放置在各处,但异常不会消失。 (我已经看这个代码几个小时了,所以我可能错过了一些东西,你们没有)。

C++ 部分(不是我的代码,但我确信它可以工作):

CXString clang_formatDiagnostic(CXDiagnostic Diagnostic, unsigned Options) {

/* Parse the hell out of a lot of data, an then make a string
   In the end, string gets wrapped in a custom struct: CXString.
 */

    return createCXString(Out.str(), true);

}

这是 CXString:

typedef struct {
  void *data;
  unsigned private_flags;
} CXString;

所以我有我的 C# 类来表示包装的 C++ 原始类:

public class Diagnostic 
    {
        private IntPtr _nativeObject;
        internal IntPtr NativeObject { get { return _nativeObject; } }

        [DllImport("libclang.dll", EntryPoint = "clang_formatDiagnostic")]
        [return: MarshalAs(UnmanagedType.LPStruct)]
        private static extern CXString FormatDiagnostic(IntPtr diag, uint options);

        public Diagnostic(IntPtr native)
        {
            _nativeObject = native;
        }

        public string GetString(DiagnosticDisplayOptions options = DiagnosticDisplayOptions.DisplaySourceLocation)
        {
            var cxstr = FormatDiagnostic(_nativeObject, (uint)options); //<-- I get the exception here
            return cxstr.GetString();
        }
    }

我需要的函数也以 C 风格(全局)实现,因此,我可以在 C# 类中留下 OO 的印象,但实际上我存储了 C++ 对象的 IntPtr 表示(_nativeObject)。所以我非常确定,存储在 _nativeObject 中的对象实际上是一个 CXDiagnostic(我得到了从同一库的另一个函数返回的引用)。

我尝试与 FormatDiagnostic 方法一起使用的实际对象是从另一个包装类 (TranslationUnit) 的构造函数初始化的:

public TranslationUnit(/*lots of params to init the unit*/)
    {
        //... there are some int conversions and initialization failsafe codes here

        //this is a property of TranslationUnit
        Diagnostics = new List<Diagnostic>();

        //GetDiagnosticsCount is also PInvoke to count CXDiagnostic objects related to the TranslationUnit
        var dgCnt = (int)GetDiagnosticsCount(_nativeObject);
        for (int i = 0; i < dgCnt; i++)
        {
            //GetDiagnostic is also PInvoke, gets the CXDiagnostic at the given index
            var diag_ptr = GetDiagnostic(_nativeObject, (uint)i);
            Diagnostics.Add(new Diagnostic(diag_ptr));
        }
        //up until now, all the calls seem to work
        //I get the expected count of diagnostics and none of the other 
        //PInvoke calls throw exceptions. They use IntPtrs, but none of them
        //use structs.
    }

因此,正如 MSDN 教程所建议的那样,我创建了一个 C# 类来将 CXString 结构编码到其中,它看起来像这样:

[StructLayout(LayoutKind.Sequential)]
public class CXString
{
    public IntPtr data;
    public uint private_flags;
}

当代码到达 FormatDiagnostic 调用时,我收到 AccessViolationException。 有什么可能出错的提示吗?

编辑:

CXDiagnostic 是原始 C++ 代码中的指针类型:

typedef void *CXDiagnostic;

最佳答案

我认为编码到 LPStruct 在这里不合适,CXString 类需要是 struct。

尝试以下代码:

public class Diagnostic 
{
    ...
    [DllImport("libclang.dll", EntryPoint = "clang_formatDiagnostic")]
    private static extern CXString FormatDiagnostic(IntPtr diag, uint options);
    ...
}

[StructLayout(LayoutKind.Sequential)]
public struct CXString
{
    public IntPtr data;
    public uint private_flags;
}

此外,您还应该注意调用约定(默认情况下为 StdCall,但例如纯 C 使用 Cdecl)和结构字节对齐。

关于c# - 将 C++ 结构编码(marshal)至 C# 类时出现 AccessViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10386139/

相关文章:

c# - ASP.NET Core Web API 验证错误处理

c++ - 依赖隐式声明的 move 构造函数是否安全?

c++ - 如何确定我输入的是什么类型

c# - 如何在构建过程中向 C# 程序添加外部信息?

c# - 无法使用 efcore 创建可为空的外键

c++ - C++结构中的位字段声明

arrays - 冷聚变 8 : Array of structs to struct of structs

c - 32 位系统中的结构填充

c# - 使用 Entity Framework 4 执行自定义 sql

c++ - 覆盖 ctype<wchar_t>