473,789 Members | 2,662 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Call C/C++ CALLBACK DLL from C# (PInvoke? Wrapper class?)

Hi,

I have an old C++ GUI Application CPPAPP.exe that calls a C DLL
library RULE.DLL through a C++ class wrapper LoadRule.CPP.

Now I need to call the C DLL RULE.DLL from C# GUI application
CSAPP.exe. I need help to convert LoadRule.CPP to a C++

BridgeDLL, and I need help on how to convert the call to the BridgeDLL
from C#.
//
*************** *************** *************** *************** *************** **********
//Rule.h: header file in C DLL RULE.DLL

#ifndef __RULE__
#define __RULE__
#ifdef __cplusplus
extern "C" {
#endif

typedef DWORD HRULE; /* Handle used in all calls */

typedef BOOL (CALLBACK* RULECALLBACK)(U INT nEvent, /* Event */
LPARAM lPar1, /*
Parameter 1 */
LPARAM lPar2, /*
Parameter 2 */
LPARAM dwExtra); /* Extra
data */
/*************** ***************/
/* Diagnostics data structure */
/*************** ***************/

typedef struct tagDIAGNOSTICS {
DWORD dwUsage; /* No. of times has beed used */
DWORD dwReserved0; /* For future use */
} DIAGNOSTICS;
typedef DIAGNOSTICS FAR * LPDIAGNOSTICS;

/*************** ********/
/* Function prototypes */
/*************** ********/

/*************** *************** *************** *************** *****/
/* Start new I/O session. */
/* Entry: hWnd = window handle of caller, could be NULL */
/* lpFn = address of callback handler */
/* lPar = extra info passed to callback function */
/* lphRule = where to copy session handle if open */
/* call was Successful. */
/* Exit: RULEERR_OK : connected OK */
/* RULEERR_MEMERR : memory allocation error */
/* RULEERR_UNKNOWN : unknown error */
/* RULEERR_NOCALLB ACKFNC : No callback function given */
/*************** *************** *************** *************** *****/

int WINAPI Rule_NewSession (HWND hWnd,
RULECALLBACK lpfnCallback,
LPARAM lPar,
HRULE FAR * lphRule);
int WINAPI Rule_EndSession (HRULE hRule);
int WINAPI Rule_ReadDiagno stics(HRULE hRule,LPDIAGNOS TICS lpDiag);
int WINAPI Rule_WriteDiagn ostics(HRULE hRule,LPDIAGNOS TICS lpDiag);
#ifdef __cplusplus
}
#endif

#endif // __RULE__

//
*************** *************** *************** *************** *************** **********
//LoadRule.h: C++ wrapper header file for DLL RULE.DLL

#ifdef __cplusplus
extern "C" {
#endif

/* Definitions for LoadRule.C module */

HINSTANCE LoadRule(LPTSTR lpszPath);
void UnloadRule(HINS TANCE hInst);

#ifdef __cplusplus
}
#endif
//
*************** *************** *************** *************** *************** **********
// LoadRule.cpp : C++ wrapper implementation file

#include "LoadRule.h "

typedef int (WINAPI *RULE_NewSessio n)(HWND hWnd,
RULECALLBACK lpfnCallback,
LPARAM lPar,
HRULE FAR * lphRule);

typedef int (WINAPI *RULE_EndSessio n)(HRULE hRule);
typedef int (WINAPI *RULE_ReadDiagn ostics)(HRULE hRule,LPDIAGNOS TICS
lpDiag);
typedef int (WINAPI *RULE_WriteDiag nostics)(HRULE hRule,LPDIAGNOS TICS
lpDiag);
static RULE_NewSession lpfnRule_NewSes sion;
static RULE_EndSession lpfnRule_EndSes sion;
static RULE_ReadDiagno stics lpfnRule_ReadDi agnostics;
static RULE_WriteDiagn ostics lpfnRule_WriteD iagnostics;

/* Local functions */

static BOOL LoadFunctionPoi nters(HINSTANCE hInst);
static void ClearFunctionPo inters(void);
HINSTANCE LoadRule(LPTSTR lpszPath)
{
HINSTANCE hInst;

hInst=LoadLibra ry(lpszPath);
if (!hInst) return hInst;

if (!LoadFunctionP ointers(hInst)) {
FreeLibrary(hIn st);
hInst=NULL;
}
return hInst;
}
void UnloadRule(HINS TANCE hInst)
{
FreeLibrary(hIn st);
ClearFunctionPo inters();
}

/*************** *************** ******* Local functions
*************** *************** **/

static BOOL LoadFunctionPoi nters(HINSTANCE hInst)
{
lpfnRule_NewSes sion = (RULE_NewSessio n)
GetProcAddress( hInst,TEXT("Rul e_NewSession")) ;
lpfnRule_EndSes sion = (RULE_EndSessio n)
GetProcAddress( hInst,TEXT("Rul e_EndSession")) ;

lpfnRule_ReadDi agnostics = (RULE_ReadDiagn ostics)
GetProcAddress( hInst,TEXT("Rul e_ReadDiagnosti cs"));
lpfnRule_WriteD iagnostics = (RULE_WriteDiag nostics)
GetProcAddress( hInst,TEXT("Rul e_WriteDiagnost ics"));

if (!lpfnRule_NewS ession ||
!lpfnRule_EndSe ssion ||
!lpfnRule_ReadD iagnostics ||
!lpfnRule_Write Diagnostics ){

ClearFunctionPo inters();
return FALSE;
}
return TRUE;
}

static void ClearFunctionPo inters(void)
{
lpfnRule_NewSes sion=NULL;
lpfnRule_EndSes sion=NULL;
lpfnRule_ReadDi agnostics=NULL;
lpfnRule_WriteD iagnostics=NULL ;

}

/*************** *************** ********* Rule.dll interface
*************** *************** *****/

int WINAPI Rule_NewSession (HWND hWnd,
RULECALLBACK lpfnCallback,
LPARAM lPar,
HRULE FAR * lphRule)
{
if (!lpfnRule_NewS ession) return RULEERR_BADHAND LE;
return (*lpfnRule_NewS ession)(hWnd,
lpfnCallback,
lPar,
lphRule);
}

int WINAPI Rule_EndSession (HRULE hRule)
{
if (!lpfnRule_EndS ession) return RULEERR_BADHAND LE;
return (*lpfnRule_EndS ession)(hRule);
}

int WINAPI Rule_ReadDiagno stics(HRULE hRule,LPDIAGNOS TICS lpDiag)
{
if (!lpfnRule_Read Diagnostics) return RULEERR_BADHAND LE;
return (*lpfnRule_Read Diagnostics)(hR ule,lpDiag);

}

int WINAPI Rule_WriteDiagn ostics(HRULE hRule,LPDIAGNOS TICS lpDiag)
{
if (!lpfnRule_Writ eDiagnostics) return RULEERR_BADHAND LE;
return (*lpfnRule_Writ eDiagnostics)(h Rule,lpDiag);
}


//
*************** *************** *************** *************** *************** **********
// CMyCEDlg.cpp: C++ application dialog

CMyCEDlg::CMyCE Dlg(CWnd* pParent /*=NULL*/)
: CDialog(CMyCEDl g::IDD, pParent)
{

// HWND m_hWnd;
// HINSTANCE m_hInstRule;
// HRULE hRule = NULL;

/* Load Rule.dll */
m_hInstRule = LoadRule(_T("\\ RULE.DLL"));
int iRet;
iRet = Rule_NewSession (m_hWnd, &MyCallback, (long)this,
&hRule);
if (iRet != RULEERR_OK)
{
UnloadRule(m_hI nstRule);
m_hInstRule = NULL;
}
else
{ // load DLL success!
// do things ....
}

}

BOOL CALLBACK CMyCEDlg::CBRul e(UINT nEvent, LPARAM lPar1, LPARAM
lPar2)
{
switch (nEvent)
{
case RULEEVENT_LINEO PENED:
//ShowMsgInfoText (_T("Line opened!"), (int) lPar1);
//bComStopped = FALSE;
break;

case RULEEVENT_LINEC LOSED:
//ShowMsgInfoText (_T("Line closed!"), (int) lPar1);
break;

case RULEEVENT_CONNE CTEDWITH:
//ShowMsgInfoText (_T("Connected with "), (int) lPar1);
break;

case RULEEVENT_OPERA TIONFAILED:
//ShowMsgInfoText (_T("Operation failed!"), (int) lPar1);
break;

}

return FALSE;
}

BOOL CALLBACK MyCallback(UINT nEvent, LPARAM lPar1, LPARAM lPar2,
LPARAM dwExtra)
{

if (dwExtra)
{
CMyCEDlg* Owner = (CMyCEDlg*) dwExtra;
return Owner->CBRule(nEven t, lPar1, lPar2);
}
else
return FALSE;
}

Mar 8 '07 #1
2 7361
Any MVP and gurus from Microsoft? Please help!

This is a very hard task involving CALLBACK functions from C library
DLL, Interop, HandleRef, PInvoke, wrapper class, DllImport Marshaling,
etc....

How to convert Rule_NewSession () from C++ to C#?

int iRet;
iRet = Rule_NewSession (m_hWnd, &MyCallback, (long)this, &hRule);

int WINAPI Rule_NewSession (HWND hWnd,
RULECALLBACK lpfnCallback,
LPARAM lPar,
HRULE FAR * lphRule)

Thanks.

Mar 9 '07 #2

<My***********@ gmail.comwrote in message
news:11******** *************@j 27g2000cwj.goog legroups.com...
Any MVP and gurus from Microsoft? Please help!

This is a very hard task involving CALLBACK functions from C library
DLL, Interop, HandleRef, PInvoke, wrapper class, DllImport Marshaling,
etc....

How to convert Rule_NewSession () from C++ to C#?
Just don't. Take your existing C++ wrapper class, change class to public
ref class, and compile with /clr to create a C++/CLI assembly that calls the
C dll and is usable from any .NET language.

The initial conversion should work pretty much that easily. After that, you
may need to go through and rewrite any wrapper functions that work with
strings, to accept System::String^ .

If you run into trouble compiling with /clr, try posting on the
microsoft.publi c.dotnet.langua ges.vc list
Mar 9 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
2011
by: Felix Kater | last post by:
Hi, in a given library I register callback functions with this function: bool set_callback(int index, int (*callback_function)(long)); I need the callback function to also pass the index which is, however, not (re-)passed by the callback function. Normally, I would just register callback functions for each
3
2677
by: John Smith | last post by:
I wrote some code in C in a dll which I would like to call from C#. However I'm stuck because of the strongly typed behavior of C# which makes limitations. Here are the prototypes for two functions which I have trouble mapping: int _SetOption(int nOption, void *pSetting); void *_GetDataField(int nType, int *npLength);
4
2403
by: Sai Kit Tong | last post by:
I have to interface managed application with my legacy dll. I have employed the wrapper approach but I have to deal with the asynchronous callback from the legacy dll, which likely goes through a thread other than the initial calling thread. I got the idea from MSDN and other articles on using the delegate. However, for garabage collection issue, I need to pin the delegate. Since my callback is asynchronous, I have been thinking about...
2
9506
by: joye | last post by:
Hello, My question is how to use C# to call the existing libraries containing unmanaged C++ classes directly, but not use C# or managed C++ wrappers unmanaged C++ classes? Does anyone know how to do that? Thanks. Tsung-Yu
7
3598
by: Kirk McDonald | last post by:
Let's say I have a function that takes a callback function as a parameter, and uses it to describe an iteration: def func(callback): for i in : callback(i) For the sake of argument, assume the iteration is something more interesting than this which relies on the callback mechanism. The function is an existing interface, and I cannot change it.
7
2620
by: harishashim | last post by:
I am wrapping a digital camera API using Managed C++ VS .NET 2003). I have this function that called as bellow in the API sample. err = PR_RC_StartViewFinder( m_hCamera, //line 1 (prContext)this, //line 2 (prViewFinderCB*)&ViewFinderCallBackFun ); //line 3 prContext is actually a typedef for unsigned long. ViewFinderCallBackFun is a callback function. There is two error that I get when i tried above code unchanged:
3
6323
by: markb | last post by:
Hi My C# app is being called from a callback from an unmanaged DLL. One of the parameters of the callback is of type BOOL. I am using PInvoke to marshal this to a (managed) bool. The problem is that no matter if we pass TRUE or FALSE, the bool is always marshalled as true. // unmanaged code in dll typedef bool (__stdcall *BoolCallBack)(short b);
6
5129
by: HolyShea | last post by:
All, Not sure if this is possible or not - I've created a class which performs an asynchronous operation and provides notification when the operation is complete. I'd like the notification to be performed on the same thread thread that instantiated the class. One way to do this is to pass an ISynchronizeInvoke into the class and use it to synchronize the callback. In the constructor of the class, could I take note of the current thread...
10
7000
by: SQACPP | last post by:
Hi, I try to figure out how to use Callback procedure in a C++ form project The following code *work* perfectly on a console project #include "Windows.h" BOOL CALLBACK MyEnumWindowsProc(HWND hwnd, LPARAM lparam) {
0
9666
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9511
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10199
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10139
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9020
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7529
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6769
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5417
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3700
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.