8

C # P / Invoke: Pointer to string as an error message

 2 years ago
source link: https://www.codesd.com/item/c-p-invoke-pointer-to-string-as-an-error-message.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C # P / Invoke: Pointer to string as an error message

advertisements

I am attempting to use llvmc as a C# library using P/Invokes(because I can't find any .NET bindings).

However, I've a problem. llvmc uses char** for error passing.

An example would be this:

char* error = NULL;
LLVMVerifyModule(PointerToSomeModule, LLVMAbortProcessAction, &error);

What should I do to allow this function to be used in C# code?

EDIT: The example I found also mentions this call:

LLVMDisposeMessage(error);

I just saw the answers and thought this could be an important detail.


A char** argument is troublesome, there is a memory management problem. If you declare the argument as "out string", the P/Invoke marshaller is going to try to free the pointer. That's very unlikely to work, it requires the string to be allocated with CoTaskMemAlloc().

The only other option you have to declare it as "out IntPtr" and marshal the string yourself with Marshal.PtrToStringAnsi(). That will work, beyond an unpluggable memory leak if LLVMC actually expects you to free the pointer. Call it a million times to verify that. There are a few odds that it won't blow since it is an error message, it might return a pointer to a string literal.

The only option left then is to write a wrapper in the C++/CLI language so you can free the pointer.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK