473,804 Members | 2,139 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C++ Call conversion

Hi,
I am a VB.net programmer who has to make use of a 3rd party Borland C++ dll.

We have a successful VC++ wrapper that presents a number of functions
that can be declared and called in VB.net

I now want to translate the wrapper to C#.
I can find my around C# in a (pardon the pun) basic fashion.

I am looking to translate the Main routine below.
I am at the first stage of emulating getting the pointer from LoadLibrary.

I have successfully used:
[DllImport ("KERNEL32.DLL" )]
public static extern long LoadLibrary(str ing lpLibFileName);

This passed back a large number when I fed it the dll name and it
passed back a smaller number when I fed a nonexistent name.

But the C++ code below gets a null back when passed a nonexistent name
so I figured I had to use a HINSTANCE like the C++ .

This led me to use a module and marshal.getHins tance
But I can't see how to assign the module to the dll I am interested in.

public long bcLoadLibrary(s tring Library)
{

long lngResult;
Module m;
//m.Name=Library; /READONLY!!

IntPtr p = new IntPtr(0);
p=Marshal.GetHI NSTANCE(m);

lngResult=(long )p;
return lngResult;
}
Am I close or deep in the weeds?
Thanks
Bob
The C++ Code snippet is

HINSTANCE pScadaDll;
TfAttach dllAttach;
TsSimAPIFuncs *pMainDllRec = NULL;
BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_c all, LPVOID
lpReserved)
{
DWORD dwResult = 0;
switch (ul_reason_for_ call)
{
case DLL_PROCESS_ATT ACH:
pScadaDll = LoadLibrary("Th eDLL.dll");
if(pScadaDll != NULL)
{
char sMsg[500];
wsprintf(sMsg, "attached TheDLL.dll Result: ");
MessageBox(NULL , sMsg, "Success", MB_OK);
dllAttach = (TfAttach)GetPr ocAddress(pScad aDll, "_dll_Attac h");

Nov 15 '05 #1
9 2164
Bob,
I have successfully used:
[DllImport ("KERNEL32.DLL" )]
public static extern long LoadLibrary(str ing lpLibFileName);

This passed back a large number when I fed it the dll name and it
passed back a smaller number when I fed a nonexistent name.
You should use IntPtr as the return type, not long.

BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_c all, LPVOID
lpReserved)
{
DWORD dwResult = 0;
switch (ul_reason_for_ call)
{
case DLL_PROCESS_ATT ACH:
pScadaDll = LoadLibrary("Th eDLL.dll");


The DllMain docs says explicitly that you must not call LoadLibrary
from within DllMain.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 15 '05 #2

Hi bclegg,

Thank you for posting in the community!

Based on my understanding, you meet the problem of P/invoke LoadLibrary in
C#.

=============== =============== ==
Actually, the return type of LoadLibrary is HMODULE, which in .Net you
should marshal it as IntPtr. So you should declare it as:
[DllImport ("KERNEL32.DLL" )]
public static extern IntPtr LoadLibrary(str ing lpLibFileName);

But, use long as the return value will not cause serious problem.(Becaus e
IntPtr is also a long type internally)

Use LoadLibrary with a nonexisted file name, the return value should be
null, which should be 0 in IntPtr.(I have tested this for you), so I can
not understand why your return value is only a "smaller number". Is the
"small number" 0?

Also, where is the main concern of you?

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #3
Hello Mattias,
Thank you for your reply.
At the risk of continuing this discussion offthread,
Could you please advise where the pScadaDll = LoadLibrary("Th eDLL.dll");
should be placed.
ie Is acceptable to make a subroutine call at this point which does it
or should the C++ DLL present a 'Connect' function to the interface.
Regards
Bob

Mattias Sjögren wrote:
Bob,

I have successfully used:
[DllImport ("KERNEL32.DLL" )]
public static extern long LoadLibrary(str ing lpLibFileName);

This passed back a large number when I fed it the dll name and it
passed back a smaller number when I fed a nonexistent name.

You should use IntPtr as the return type, not long.
BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_c all, LPVOID
lpReserved)
{
DWORD dwResult = 0;
switch (ul_reason_for_ call)
{
case DLL_PROCESS_ATT ACH:
pScadaDll = LoadLibrary("Th eDLL.dll");

The DllMain docs says explicitly that you must not call LoadLibrary
from within DllMain.

Mattias


Nov 15 '05 #4
Hello Jeffery,
Thanks for your reply.

Your declaration works!

My main concern is that we have to interact with a
3rd party dll which uses a pointer as the way in.
ie. result = pointer-> SomeFunction

One of our programmers wrote a C++ wrapper which presents the functions
at the interface in a declarable manner.
ie.
Declare Sub SomeFunction Lib "D:\thepath\The DLL.dll"

I would like to move this functionality into C# and present the
functions via a C# component that doesn't have to call the C++ wrapper.

Thanks
Bob
Jeffrey Tan[MSFT] wrote:
Hi bclegg,

Thank you for posting in the community!

Based on my understanding, you meet the problem of P/invoke LoadLibrary in
C#.

=============== =============== ==
Actually, the return type of LoadLibrary is HMODULE, which in .Net you
should marshal it as IntPtr. So you should declare it as:
[DllImport ("KERNEL32.DLL" )]
public static extern IntPtr LoadLibrary(str ing lpLibFileName);

But, use long as the return value will not cause serious problem.(Becaus e
IntPtr is also a long type internally)

Use LoadLibrary with a nonexisted file name, the return value should be
null, which should be 0 in IntPtr.(I have tested this for you), so I can
not understand why your return value is only a "smaller number". Is the
"small number" 0?

Also, where is the main concern of you?

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.


Nov 15 '05 #5

Hi Bob,

Based on my understanding, your dll may use some functions that is inside
another dll, so you want to load that dll for use.

I think you should specify a variable for determine the loading of that
dll, when you want to use the functions, you can judge the variable, if the
dll is not loaded, then you can load that dll. Through this way, you have
delayed the loading of the dll until your dll is initialized probably.

Thanks.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #6
Thank you for your reply.
I have altered the C++ wrapper.
Regards
Bob
Mattias Sjögren wrote:
Bob,

I have successfully used:
[DllImport ("KERNEL32.DLL" )]
public static extern long LoadLibrary(str ing lpLibFileName);

This passed back a large number when I fed it the dll name and it
passed back a smaller number when I fed a nonexistent name.

You should use IntPtr as the return type, not long.
BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_c all, LPVOID
lpReserved)
{
DWORD dwResult = 0;
switch (ul_reason_for_ call)
{
case DLL_PROCESS_ATT ACH:
pScadaDll = LoadLibrary("Th eDLL.dll");

The DllMain docs says explicitly that you must not call LoadLibrary
from within DllMain.

Mattias


Nov 15 '05 #7
Hi bclegg,

Thanks very much for your feedback.

If you have any further concern, please feel free to feedback. We will help
you.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #8
Hello Jeffery,
Thanks again,
I have just have one further question if I may.
The 3rd party dll comes with a C++ header file that has some type
definitions that I can't see how to convert to C#

eg typedef void (*Tfsa_SetCurDa tabase)(const char *prmDatabase);

Once it declares a number of these it then declares a struct containing
them.
One entry from which is
Tfsa_SetCurData base SetCurDatabase;

The struct is then exposed along with a function for version checking.
typedef bool __declspec(dlle xport) (*TfAttach)(TsS imAPIFuncs
**prmSimAPIFunc s, const char *prmVersion);

extern TsSimAPIFuncs simAPI;

The C++ wrapper's global variables and connecting call are :
HINSTANCE pDll;
TfAttach dllAttach;
TsSimAPIFuncs *pMainDllRec = NULL;

void WTS_API LoadDLL()
{
DWORD dwResult = 0;
pDll = LoadLibrary("Th eDLL.dll");
if(pDll != NULL)
{

dllAttach = (TfAttach)GetPr ocAddress(pDll, "_dll_Attac h");
if(dllAttach != NULL)
{
if(!dllAttach(& pMainDllRec, CONST_API_VERSI ON))
...
AND away we go, either error handling or successfully exiting. If a
successful exit then the wrapper
dereferences pMainDllRec to get to the various functions in the struct.
eg
void WTS_API SetCurDatabase( const char *prmDatabase)
{
pMainDllRec->SetCurDatabase (prmDatabase);
}

My questions are:
1) Can I emulate these parameterised typedefs in C#
2) If so would you be able to show me how to write the equivalent
GetProcAddress.
regards
Bob Clegg

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #9
Jeffrey,
But, use long as the return value will not cause serious problem.
I think getting bogus return values is a pretty serious problem, and
that's usually the result if you incorrectly use long as the return
type.

(Because IntPtr is also a long type internally)


Not on Win32 it isn't.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 15 '05 #10

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

Similar topics

10
2087
by: sjbrown8 | last post by:
I have the piece of code below, and when i try compiling with the line g++ 753075304.cpp I get the following error message: 753075304.cpp: In function 'int main()': 753075304.cpp:29: error: 'plus' was not declared in this scope I've gone over the code several times line by lin, and my eyes are
15
5164
by: Anonymousgoogledeja | last post by:
Hi all, since the function atof, atoi, _atoi64, atol returned value are Return Values Each function returns the double, int, __int64 or long value produced by interpreting the input characters as a number. The return value is 0 (for atoi and _atoi64), 0L (for atol), or 0.0 (for atof) if the input
11
7627
by: Steve Gough | last post by:
Could anyone please help me to understand what is happening here? The commented line produces an error, which is what I expected given that there is no conversion defined from type double to type Test. I expected the same error from the following line, but it compiles fine. The double is silently truncated to an int and then fed in to the implicit conversion operator. Why does this happen? Is there any way that I can keep the implicit...
5
10997
by: rolandz | last post by:
Hi, Maybe somebody has been fighting with the problem that I do, currently. I have a class that has method f(). The two versions of the f() method accept different objects: Int and Short. These objects have constructors that allow implicit conversions from simple types. All this has been defined as follows: <code> class Int
10
16678
by: ravi | last post by:
Hi, i am a c++ programmer, now i want to learn programming in c also. so can anybody explain me the difference b/w call by reference and call by pointer (with example if possible).
8
3104
by: xtrigger303 | last post by:
Hi to all, I'm working on a smart pointer implementation and I'm trying to get automatic type conversion between different pointer types. I stumbled upon something weird (at least for me) I summarized it in the code below. I was expecting both things at the end to work or not work at all.... Any insight? Thanks in advance, Francesco
7
1646
by: cppquester | last post by:
What does this code do? #include <iostream> class A { public: A() { std::cout << "A::A()" << std::endl;} };
12
7222
by: Rahul | last post by:
Hi Everyone, I have the following code and i'm able to invoke the destructor explicitly but not the constructor. and i get a compile time error when i invoke the constructor, why is this so? class Trial { public: Trial() {
15
1885
by: asm23 | last post by:
Hi, everyone, I'm studying the <<Thinking in C++>volume Two. In Chapter One, the example code : Auto_ptr.cpp //------------------------------------------------------- #include <memory> #include <iostream> #include <cstddef> using namespace std; class TraceHeap { int i;
0
1188
by: James Kanze | last post by:
On Oct 6, 3:59 pm, microcassanova <mangal.pa...@gmail.comwrote: I presume you mean explicit, but what does that change? And what is the relationship with data loss. (Most of my constructors are declared explicit, but the reason has nothing
0
9714
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
9594
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
10600
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
10351
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
10096
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
9174
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
7638
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
6866
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();...
1
4311
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

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.