473,778 Members | 1,910 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PInvoke with callback & function pointers: struct or class?

2 New Member
I need to use an unmanaged c++ dll which uses structs that contain callbacks and also functions. I have included the appropriate c++ definitials and my c# translations below.

I first defined the parameters as c# structs, but when I tried the call (to RtcInitialize) I got the following error:

MarshalDirectiv eException
Method's type signature is not PInvoke compatible.

I then changed the structs to classes but now I get the following error:

AccessViolation Exception
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Can anyone see what I am doing wrong?

Thanks,

Stuart


The first c++ definitions are:

DLL_FUNCTION RtcConfigHandle * RtcInitialize(i nt major_version, int minor_version, RtcInitParams *initParams);

typedef struct DLL_FUNCTION {
char* configPath;
RtcLogMode logMode;
const char* logPath;
void (*rtcOnLog)(con st char *logMessage);
} RtcInitParams;

typedef struct DLL_FUNCTION {
int (*getUser)(char *userId, int len);
int (*setUser)(cons t char *userId, const char *password);
int (*getProxyServe rAddresses)(cha r *addresses, int len);
int (*setProxyServe rAddresses)(con st char *addresses);
int (*getLocalIPAdd ress)(char *localIf, int len);
int (*setLocalIPAdd ress)(const char *localIp);
int (*findActiveLoc alIPAddress)(ch ar *activeIPAddres s, int len);
int (*getLocalMedia Address)(char *localMediaIf, int len);
int (*setLocalMedia Address)(const char *localMediaIp);
int (*getSipPort)(i nt *port);
int (*setSipPort)(i nt port);
int (*getHttpProxyS ettings)(int *autoDetect, int *direct, char *addr, int addrLen, char *script, int scriptLen, char *cred, int credLen);
int (*setHttpProxyD irect)();
int (*setHttpProxyA utoDetect)();
int (*setHttpProxyA ddress)(const char *addr);
int (*setHttpProxyP AC)(const char *pacAddr);
int (*setHttpProxyC redentials)(con st char *user, const char *password);
int (*getAlwaysTunn elMedia)(int *alwaysTunnel);
int (*setAlwaysTunn elMedia)(int alwaysTunnel);
int (*getSignalingM ode)(RtcSignali ngMode *mode);
int (*setSignalingM ode)(RtcSignali ngMode mode);
int (*getLocalTunne lPort)(int *tunnelPort);
int (*getFirewallTy pe)(char *fwType, int len);
int (*setSignalHand lerMask)(RtcSig nalMask mask);
int (*setLogLevel)( RtcLogLevel logLevel);
int (*setLogGroups) (const char* groups);
int (*getVersion)(c har *version, int len);
int (*getIceEnabled )(int* enable);
int (*setIceEnabled )(int enable);
int (*getStunEnable d)(int* enable);
int (*setStunEnable d)(int enable);
int (*getTurnEnable d)(int* enable);
int (*setTurnEnable d)(int enable);
int (*getStunServer Addresses)(char *addresses, int len);
int (*setStunServer Addresses)(cons t char *addresses);
int (*getTurnServer Addresses)(char *addresses, int len);
int (*setTurnServer Addresses)(cons t char *addresses);
int (*setSocksEnabl ed)(int enable);
int (*setSocksAddre ss)(char* addr, int port);
int (*getSocksAddre ss)(char* addr, int addrLen, int* port);
int (*closeLogFileA bnormally)(char * logfilename, int len);
} RtcConfigHandle ;

which I have translated as:

[DllImport("rtcS dk.dll", SetLastError = true, CharSet = CharSet.Auto, CallingConventi on = CallingConventi on.StdCall)]
private static extern RtcConfigHandle RtcInitialize(i nt major_version, int minor_version, ref RtcInitParams initParams);

[StructLayout(La youtKind.Sequen tial, Pack=4)]
private struct RtcInitParams
{
public string configPath;
public RtcLogMode logMode; // this is an enum
public string logPath;
[MarshalAs(Unman agedType.Functi onPtr)]
public rtcOnLogDelegat e rtcOnLog;
}


[StructLayout(La youtKind.Sequen tial, Pack = 4)]
private struct RtcConfigHandle
{
[MarshalAs(Unman agedType.Functi onPtr)]
public getUserDelegate getUser;
[MarshalAs(Unman agedType.Functi onPtr)]
public setUserDelegate setUser;
[MarshalAs(Unman agedType.Functi onPtr)]
public getProxyServerA ddressesDelegat e getProxyServerA ddresses;
[MarshalAs(Unman agedType.Functi onPtr)]
public setProxyServerA ddressesDelegat e setProxyServerA ddresses;
[MarshalAs(Unman agedType.Functi onPtr)]
public getLocalIPAddre ssDelegate getLocalIPAddre ss;
[MarshalAs(Unman agedType.Functi onPtr)]
public setLocalIPAddre ssDelegate setLocalIPAddre ss;
[MarshalAs(Unman agedType.Functi onPtr)]
public findActiveLocal IPAddressDelega te findActiveLocal IPAddress;
[MarshalAs(Unman agedType.Functi onPtr)]
public getLocalMediaAd dressDelegate getLocalMediaAd dress;
[MarshalAs(Unman agedType.Functi onPtr)]
public setLocalMediaAd dressDelegate setLocalMediaAd dress;
[MarshalAs(Unman agedType.Functi onPtr)]
public getSipPortDeleg ate getSipPort;
[MarshalAs(Unman agedType.Functi onPtr)]
public setSipPortDeleg ate setSipPort;
[MarshalAs(Unman agedType.Functi onPtr)]
public getHttpProxySet tingsDelegate getHttpProxySet tings;
[MarshalAs(Unman agedType.Functi onPtr)]
public setHttpProxyDir ectDelegate setHttpProxyDir ect;
[MarshalAs(Unman agedType.Functi onPtr)]
public setHttpProxyAut oDetectDelegate setHttpProxyAut oDetect;
[MarshalAs(Unman agedType.Functi onPtr)]
public setHttpProxyAdd ressDelegate setHttpProxyAdd ress;
[MarshalAs(Unman agedType.Functi onPtr)]
public setHttpProxyPAC Delegate setHttpProxyPAC ;
[MarshalAs(Unman agedType.Functi onPtr)]
public setHttpProxyCre dentialsDelegat e setHttpProxyCre dentials;
[MarshalAs(Unman agedType.Functi onPtr)]
public getAlwaysTunnel MediaDelegate getAlwaysTunnel Media;
[MarshalAs(Unman agedType.Functi onPtr)]
public setAlwaysTunnel MediaDelegate setAlwaysTunnel Media;
[MarshalAs(Unman agedType.Functi onPtr)]
public getSignalingMod eDelegate getSignalingMod e;
[MarshalAs(Unman agedType.Functi onPtr)]
public setSignalingMod eDelegate setSignalingMod e;
[MarshalAs(Unman agedType.Functi onPtr)]
public getLocalTunnelP ortDelegate getLocalTunnelP ort;
[MarshalAs(Unman agedType.Functi onPtr)]
public getFirewallType Delegate getFirewallType ;
[MarshalAs(Unman agedType.Functi onPtr)]
public setSignalHandle rMaskDelegate setSignalHandle rMask;
[MarshalAs(Unman agedType.Functi onPtr)]
public setLogLevelDele gate setLogLevel;
[MarshalAs(Unman agedType.Functi onPtr)]
public setLogGroupsDel egate setLogGroups;
[MarshalAs(Unman agedType.Functi onPtr)]
public getVersionDeleg ate getVersion;
[MarshalAs(Unman agedType.Functi onPtr)]
public getIceEnabledDe legate getIceEnabled;
[MarshalAs(Unman agedType.Functi onPtr)]
public setIceEnabledDe legate setIceEnabled;
[MarshalAs(Unman agedType.Functi onPtr)]
public getStunEnabledD elegate getStunEnabled;
[MarshalAs(Unman agedType.Functi onPtr)]
public setStunEnabledD elegate setStunEnabled;
[MarshalAs(Unman agedType.Functi onPtr)]
public getTurnEnabledD elegate getTurnEnabled;
[MarshalAs(Unman agedType.Functi onPtr)]
public setTurnEnabledD elegate setTurnEnabled;
[MarshalAs(Unman agedType.Functi onPtr)]
public getStunServerAd dressesDelegate getStunServerAd dresses;
[MarshalAs(Unman agedType.Functi onPtr)]
public setStunServerAd dressesDelegate setStunServerAd dresses;
[MarshalAs(Unman agedType.Functi onPtr)]
public getTurnServerAd dressesDelegate getTurnServerAd dresses;
[MarshalAs(Unman agedType.Functi onPtr)]
public setTurnServerAd dressesDelegate setTurnServerAd dresses;
[MarshalAs(Unman agedType.Functi onPtr)]
public setSocksEnabled Delegate setSocksEnabled ;
[MarshalAs(Unman agedType.Functi onPtr)]
public setSocksAddress Delegate setSocksAddress ;
[MarshalAs(Unman agedType.Functi onPtr)]
public getSocksAddress Delegate getSocksAddress ;
[MarshalAs(Unman agedType.Functi onPtr)]
public closeLogFileAbn ormallyDelegate closeLogFileAbn ormally;
}

private delegate void rtcOnLogDelegat e(string logMessage);
private delegate int getStatusDelega te(ref RtcEventState state);
private delegate int rtcStopDelegate ();
private delegate int rtcLockDelegate ();
private delegate int rtcUnlockDelega te();
private delegate int rtcIsLockedDele gate(ref int locked);
private delegate void rtcOnEventDeleg ate(IntPtr userdata, RtcEventState state, RtcEventSubStat e substate, string substateDescrip tion);
private delegate int getUserDelegate (ref string userId, int len);
private delegate int setUserDelegate (string userId, string password);
private delegate int getProxyServerA ddressesDelegat e(ref string addresses, int len);
private delegate int setProxyServerA ddressesDelegat e(string addresses);
private delegate int getLocalIPAddre ssDelegate(ref string localIf, int len);
private delegate int setLocalIPAddre ssDelegate(stri ng localIp);
private delegate int findActiveLocal IPAddressDelega te(ref string activeIPAddress , int len);
private delegate int getLocalMediaAd dressDelegate(r ef string localMediaIf, int len);
private delegate int setLocalMediaAd dressDelegate(s tring localMediaIp);
private delegate int getSipPortDeleg ate(ref int port);
private delegate int setSipPortDeleg ate(int port);
private delegate int getHttpProxySet tingsDelegate(r ef int autoDetect, ref int direct, ref string addr, int addrLen, ref string script, int scriptLen, ref string cred, int credLen);
private delegate int setHttpProxyDir ectDelegate();
private delegate int setHttpProxyAut oDetectDelegate ();
private delegate int setHttpProxyAdd ressDelegate(st ring addr);
private delegate int setHttpProxyPAC Delegate(string pacAddr);
private delegate int setHttpProxyCre dentialsDelegat e(string user, string password);
private delegate int getAlwaysTunnel MediaDelegate(r ef int alwaysTunnel);
private delegate int setAlwaysTunnel MediaDelegate(i nt alwaysTunnel);
private delegate int getSignalingMod eDelegate(ref RtcSignalingMod e mode);
private delegate int setSignalingMod eDelegate(RtcSi gnalingMode mode);
private delegate int getLocalTunnelP ortDelegate(ref int tunnelPort);
private delegate int getFirewallType Delegate(ref string fwType, int len);
private delegate int setSignalHandle rMaskDelegate(R tcSignalMask mask);
private delegate int setLogLevelDele gate(RtcLogLeve l logLevel);
private delegate int setLogGroupsDel egate(string groups);
private delegate int getVersionDeleg ate(ref string version, int len);
private delegate int getIceEnabledDe legate(ref int enable);
private delegate int setIceEnabledDe legate(int enable);
private delegate int getStunEnabledD elegate(ref int enable);
private delegate int setStunEnabledD elegate(int enable);
private delegate int getTurnEnabledD elegate(ref int enable);
private delegate int setTurnEnabledD elegate(int enable);
private delegate int getStunServerAd dressesDelegate (ref string addresses, int len);
private delegate int setStunServerAd dressesDelegate (string addresses);
private delegate int getTurnServerAd dressesDelegate (ref string addresses, int len);
private delegate int setTurnServerAd dressesDelegate (string addresses);
private delegate int setSocksEnabled Delegate(int enable);
private delegate int setSocksAddress Delegate(ref string addr, int port);
private delegate int getSocksAddress Delegate(ref string addr, int addrLen, ref int port);
private delegate int closeLogFileAbn ormallyDelegate (ref string logfilename, int len);
Feb 25 '08 #1
1 6663
eastlands
2 New Member
Strange how you see a way forward within minutes of posting a question...

I changed the return type of the methods to IntPtr and then used Marshal.PtrToSt ructure to get back to the managed struct.

Although I haven't completed this work, it seems to be holding together now.

Stuart


I need to use an unmanaged c++ dll which uses structs that contain callbacks and also functions. I have included the appropriate c++ definitials and my c# translations below.

I first defined the parameters as c# structs, but when I tried the call (to RtcInitialize) I got the following error:

MarshalDirectiv eException
Method's type signature is not PInvoke compatible.

I then changed the structs to classes but now I get the following error:

AccessViolation Exception
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Can anyone see what I am doing wrong?

Thanks,

Stuart
Feb 25 '08 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

0
1756
by: vijaya | last post by:
I've to invoke a unmanaged dll fucntion in C# which uses a callback fucntion.The unmanaged dll fucntion is as follows **************************************** The Original Fucntion in the dll **************************************** int PBORCA_LibraryDirectory ( HPBORCA hORCASession, LPSTR lpszLibName, LPSTR lpszLibComments, int iCmntsBuffSize, PBORCA_LISTPROC pListProc, LPVOID pUserData );
0
338
by: vijaya | last post by:
I've a problem with PInvoke.I've to invoke a unmanaged dll fucntion in C# which uses a callback fucntion.Please apologise for this lenghty message and render ur kind help. The original dll function and my C# code has been given below along with the error message. Error: The return code is 0 which means the fucntion has executed successfully. But I'm not getting the correct values in the structure pborcadirentry. Note: I've tried GC...
2
1794
by: MR | last post by:
help! I have an unmanaged DLL that I do not have the source code, so i can't recompile or make changes. the DLL requires a callback function. I would like to implement the callback method in a managed class. The unmanaged DLL gets the address of the callback in a struct (someStruct below) that is passed as a parameter. I can't seem to figure out how to pass the "unmanaged" address of a managed method to be uses as a callback. I would...
6
2211
by: Pucca | last post by:
I have a program that originally compiles into a exe file. I changed the compile option to generate dll file. This program calls a com component. Can I use pinvoke in C# to call it? The following is the main dll file. #include "stdafx.h" #define MAX_ADSPATH_CHARS 2048 //*************************************************************************** // local function prototypes
4
2828
by: Kyku | last post by:
Hello all, I'm in a process of writing a small Linux C++ program for discovering repeaded files over a filesystem. One part of this task is traversing a directory structure. This is done by the following recursive function. Since I'd like it to be general enough to handle function pointers and function objects I've made it a template. template <typename CallBack> void Traverse(const std::string& path, CallBack& callback) throw
2
7361
by: MyCrystalGift | last post by:
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#.
6
1737
by: gregarican | last post by:
I am trying to port a legacy CTI application written in another programming language to C# 2005. From my initial research into it I see I can utilize the DllImport method to tap into the DLL file (which is CTSA32.DLL). From there I have documented API for the various C methods that are invoked, most all of which have an in and an out. You pass in a data structure and get a data structure returned back. What's the most straightforward way...
14
3796
by: Mohamed Mansour | last post by:
Hey there, this will be somewhat a long post, but any response is appreciated! I have done many PInvoke in the past from C++ to C#, but I did PInvoke within C# not C++/CLI. Can someone explain more why C++/CLI would be better to PInvoke than doing the PInvoke in C#? Because, usually in C# as you already know we use DLLImport and extern
0
1273
by: Michibeck | last post by:
Hi, I need some help regarding callback function written in c# and called from unmanaged c code. (c dll). The problem is that the callback function crashs after the first call with a memory access exception. I tried to protect the callback function to be handle by the GC but it doesn't work. What could I do to fix that problem?? Thanks, Michibeck C Code: /*********************************************************************** **
0
9629
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
10298
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10069
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
9923
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8957
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...
0
6723
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
5370
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...
1
4033
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2865
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.