Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi.
I wanna call callback function of C# project in C++ dll. Function in C++ DLL is like this.
C++
extern "C" __declspec(dllexport) DWORD __stdcall SD_KM_Recognize(
SD_KM_OCR_RESULT* lpResults, 
DWORD dwLength, 
int  ( *CheckInterupt)(int nCommand) = NULL,
void ( *TotalProgressChangeCallBack)(int nLower, int nUpper, int nPos, int nStep, int nStepIncrement, LPCSTR lpszTitle) = NULL
);

In C# project, I've load C++ DLL like this.
C#
delegate void CallbackProgressChange(Int32 nLower, Int32 nUpper, Int32 nPos, Int32 nStep, Int32 nStepIncrement, String szBuffer);

[DllImport("JSOCRBridge.dll", EntryPoint = "SD_KM_Recognize", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
static extern UInt32 SD_KM_Recognize(SD_KM_OCR_RESULT[] result, UInt32 nResultLen, IntPtr nStatus, CallbackProgressChange callback);

Whenever I call SD_KM_Recognize function in C# project, error occurred.
C#
CallbackProgressChange recogcallback = new CallbackProgressChange(ProgressChangeCallBack);
SD_KM_Recognize(ret, 10240, IntPtr.Zero, recogcallback);

Error is "Memory write protection error!".

Reason is that TotalProgressChangeCallBack function write memories into lpszTitle parameter.

How can I fix it?
Posted
Comments
Bernhard Hiller 18-Sep-14 8:38am    
How is "ret" defined and initialised?
Did you check that SD_KM_OCR_RESULT is correctly defined in C#?

1 solution

this[^] article might help.
 
Share this answer
 
Comments
WuRunZhe 18-Sep-14 7:45am    
Your answer is good but it't not proper for my question.
V. 18-Sep-14 7:53am    
long shot, but try changing the String parameter to a StringBuilder. If that doesn't work, try checking out the C# Marshal functions. My guess is that the String class is managed while the LPCSTR is obviously not.
A very long time ago we had a similar issue and we fixed it, if I remember correctly, by using the StringBuilder.
WuRunZhe 18-Sep-14 8:31am    
The main problem is that CPP function make it's local character array variable and send it to C# call back function.

If send null parameter to c# callback, there is no problem. But if send character array variable which is newly created into code, "Memory write protection error" occurred.

I can not find the reason. In c# callback function, I only use parameter not operate it. If I operate it, error could be realized but not.

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