Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I have a code written in C++ which i need to consume in C# Application.
Below are the syntax's of the two methods which i need to use in my C# application:
C++
long __declspec (dllimport) MyMethod1(const wchar_t* inputFileName, const wchar_t* outputFileName)

__declspec (dllimport) int __stdcall MyMethod2(void ** pMyVoidPtr, MY_CUSTOM_STRUCT* pMyCustomStruct);

I could use them in my C++ Application as below:
C++
MyMethod1(_T("C:\\InputFile.txt"), _T("C:\\OutputFile.txt"));

MY_CUSTOM_STRUCT myCustomStruct;

void* pVoidPtr = NULL;

MyMethod2(&pVoidPtr, &myCustomStruct);

In C++ Application, i could get the desired results. But in C# Application, the Pointer pVoidPtr always returns NULL.

I have tried using ref, out IntPtr as parameters but everything failed.

Could anyone provide me the syntax for the same in C# Application (For both the methods)?

Thanks and Regards,
Kishor Reddy

What I have tried:

C++
[DllImport("Exported Dll Path")]
long static extern MyMethod1(string strInputName, string strOutputName);

[DllImport("Exported Dll Path")]
int static extern MyMethod2(out IntPtr pVoidPtr, MY_CUSTOM_STRUCT myCustomStruct);

[DllImport("Exported Dll Path")]
int static extern MyMethod2(out IntPtr pVoidPtr, IntPtr myCustomStruct);
Posted
Updated 28-Mar-17 5:50am
v3
Comments
Garth J Lancaster 28-Mar-17 1:28am    
ok ...

why are you using DllImport on the c++ side ? ie "long __declspec (dllimport)" shouldn't you be exporting these functions ?

I'd also look at the 'Data Structures' discussion between David and Luke on this article as a response to the 'same sort of thing' about marshalling structs https://www.codeproject.com/Articles/138614/Advanced-Topics-in-PInvoke-String-Marshaling

.. and maybe this article since David mentions it http://www.developerfusion.com/article/84519/mastering-structs-in-c/

1 solution

At first Garth is right you must export the functions to access them from outside.

And you shouldnt import memory or allocated objext from one runtime (C++) into another (C#). You wont like the pitfalls. Provide a big enough buffer from C#, maybe after asking C++ with an explicit function and than allocate and execute the call.

Read my article for some simple way to deal that issue. At the end is also a link where a more complexer scenario is handled.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900