开发者

How to call a C++ function that takes a reference from C# code

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜