Take the 2-minute tour ×

HI, I have a C++ function like the following:

int ShowJob(const JobData& data);

How does this translate to a DLLImport statement which I can use to call the function from C#?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

This could only work if JobData is a structure. You're dead in the water if it is a class, you cannot create a C++ class instance in C#. You don't have access to the constructor and destructor.

The "const" keyword is an attribute checked by the C++ compiler, it has no relevance to C# code. A C++ reference is a pointer under the hood, you'll get one by declaring the argument with "ref". You're likely to have a problem getting the "ShowJob" export name right, it is normally decorated by the C++ compiler. You'd suppress that decoration by prefixing the function with extern "C" in the C++ code. If you cannot change the C++ code then you can find the exported name by running Dumpbin.exe /exports on the DLL.

Putting this all together, the declarations ought to resemble something like this:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
private struct JobData {
  // members...

[DllImport("something.dll", EntryPoint = "?ShowJob@@YAHABUJobData@@@Z", CallingConvention = CallingConvention.Cdecl)]
private static extern int ShowJob(ref JobData data);

Lot's of guess work going on here, you'll need to verify this with your actual C++ code. If the JobData argument is in fact a class then you'll need to write a ref class wrapper in the C++/CLI language.

share|improve this answer
Great, thanks. The main missing part was that C++ reference is a pointer under the hood. Do you have a link to a documentation page that explicitly says this? –  splintor May 20 '10 at 16:33
Compiler internals are never documented, they are reverse-engineered. –  Hans Passant May 20 '10 at 16:40

I'd guess it behaves like a pointer under the hood, so treat it as such. Ironically, this is done by declaring it as a reference parameter.

public static extern int ShowJob(ref JobData data);
share|improve this answer

Your Answer


