1

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#?

0

2 Answers 2

2

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.

[DLLImport(DLLName)]
public static extern int ShowJob(ref JobData data);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

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?
Compiler internals are never documented, they are reverse-engineered.

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.