2

I have a C++ DLL with partial documentation only and no source code access. I need to use functions of this C++ library in my C# application. This is what I have so far:

[DllImport(cpplib.dll)]
public static extern long someFunctionsWithNoParameters();

When I declare and call a function from the C++ DLL in my C# application like this (function with no arguments) and than call it, it works, the function returns a long value returned by the C++ function.

However I don't know how to handle functions with pointer or reference parameters, or parameters defined as in and out by the C++ function. For example this C++ function:

long functionWithParameters(long &State, char *pName, int nLen)

This is how the function is declared (I have access to the header file of the DLL, but not to the source). The parameters State and pName are declared as out parameters and the parameter nLen is declared as in parameter. How do I declare this C++ function in my C# application under the [DllImport] line and than use it (what form of parameters should I pass in and how to read the out parameters)? Is there some conversion convention between the C/C++ pointer and reference types to some C# types?

Thank you!

2
  • The question is too broad to answer here. See msdn.microsoft.com/en-us/library/ms173184.aspx. Post specific questions as they come up. Commented Nov 10, 2014 at 7:55
  • Is there an auto converter for this? Commented Jun 30, 2022 at 8:25

1 Answer 1

1

You need to declare a matching call convention for the imported function. You could try __cdecl or __stdcall, like this:

[DllImport(cpplib.dll, CallingConvention=CallingConvention.Cdecl)]
public static extern long someFunctionsWithNoParameters();

About pointers and references (which are the same in most practical implementations), you need to use unsafe context and C# pointers, consult MSDN for more detail.

Sign up to request clarification or add additional context in comments.

2 Comments

"About pointers and references (which are the same in most practical implementations), you need to use unsafe context and C# pointers" No, ref will work fine for references, and out or ref can be used for pointers.
Ah nice, I'll remember that ^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.