将C ++结构封送到C#类时的AccessViolationException

时间:2012-04-30 15:20:55

标签: c# c++ struct pinvoke marshalling

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

一切都很闪亮,直到我试图调用返回结构的C ++方法。 我做了所有事情by the book,但是当调用此方法时,我得到了AccessViolationException。

现在,我读到这可能是因为有些东西搞砸了对象的记忆图像。我检查并重复检查,如果我已经把所有的arrtibute和什么都没有,但Exception不会消失。 (我一直在看这段代码几个小时,所以我可能错过了一些东西,你们不这样做。)

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;

1 个答案:

答案 0 :(得分:2)

我认为编组到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)和结构字节对齐。