Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7912291
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T13:33:53+00:00 2026-06-03T13:33:53+00:00

I’m trying to wrap a C++ library (libclang) into a C# wrapper, using PInvoke.

  • 0

I’m trying to wrap a C++ library (libclang) into a C# wrapper, using PInvoke.

Everything was shiny, until I tried to call a C++ method that returns a struct.
I did everything by the book, but when this method gets called, I get AccessViolationException.

Now, I read that it’s probably because there’s something messed up with the memory image of the objects. I checked and doublechecked if I’ve put all the arrtibutes and what nots everywhere but the Exception won’t go away. (I’ve been looking at this code for hours, so I may have missed some things, you guys don’t).

The C++ part (not my code, but I’m sure that it works):

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);

}

Here’s CXString:

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

So I have my C# classes to represent the wrapped C++ originals:

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();
        }
    }

The functions I need are also implemented in a C taste (global) so, I can make an impression of OO in my C# classes, but in fact I store the IntPtr representations of the C++ objects (_nativeObject). So I’m pretty sure, that the object stored in the _nativeObject is in fact an CXDiagnostic (I got the reference returned from another function of the same library).

The actual object that I’m trying to use with FormatDiagnostic method gets initialized from the constructor of another wrapper class (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.
    }

So as the MSDN tutorial suggested, I’ve made a C# class to Marshal the CXString struct into, and it looks like this:

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

I get the AccessViolationException when the code reaches FormatDiagnostic call.
Any tips where it could have gone wrong?

EDIT:

CXDiagnostic is a pointer type in the original C++ code:

typedef void *CXDiagnostic;
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T13:33:54+00:00Added an answer on June 3, 2026 at 1:33 pm

    I think marshalling to LPStruct is not proper here and the CXString class needs to be struct.

    Try the following code:

    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;
    }
    

    Also, you should take care of the calling convention (StdCall by default, but for example pure C use Cdecl) and the struct byte alignment.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,
I am reading a book about Javascript and jQuery and using one of the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.