473,695 Members | 2,227 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Calling native C++ function using DefinePInvokeMe thod and returning a calculated value as a pointer/by reference

Hi
I need to call a native function in a C++ dll from my C#. The C++ function
declaration is shown below.

The C# code that I have been trying to perform the call is also shown below.
All it is trying to do is to pass in two integers, add them together and
return the result in the third parameter (byref/as a pointer).

The problem is how do I specify the third parameter to be a pointer to type
int?

Thanks for any help in advance.

Marek

C++ function declaration
=============== =============== =============== =============== =============== =====
extern "C"
{
__declspec( dllexport ) void WINAPI SumIntWithRef(i nt a, int b, int* pc)
{
*pc = a + b;
}
}

C# call
=============== =============== =============== =============== =============== =============== ==

string dllName = @"NativeFunctio nDLL.dll";
string entryPointName = "SumIntWithRef" ;

//...Set up the return value:
Type returnType = null;

//...Set up the parameters:
Type[] parameterTypes = new Type[3];
object[] parameterValues = new object[3];

parameterTypes[0] = typeof(int);
parameterValues[0] = 2;

parameterTypes[1] = typeof(int);
parameterValues[1] = 3;

parameterTypes[2] = typeof(int); //...How should this one be
specified?
parameterValues[2] = 0;

// Create a dynamic assembly and a dynamic module
AssemblyName assemblyName = new AssemblyName();
assemblyName.Na me = "tempDll";
AssemblyBuilder assemblyBuilder =
AppDomain.Curre ntDomain.Define DynamicAssembly (assemblyName,
AssemblyBuilder Access.Run);
ModuleBuilder moduleBuilder =
assemblyBuilder .DefineDynamicM odule("tempModu le");

// Dynamically construct a global PInvoke signature
// using the input information
MethodBuilder methodBuilder =
moduleBuilder.D efinePInvokeMet hod(entryPointN ame,
dllName,
MethodAttribute s.Static
| MethodAttribute s.Public | MethodAttribute s.PinvokeImpl,
CallingConventi ons.Standard,
returnType,
parameterTypes,
CallingConventi on.Winapi,
CharSet.Ansi);

//...This global method is now complete:
methodBuilder.S etImplementatio nFlags(MethodIm plAttributes.Pr eserveSig);
moduleBuilder.C reateGlobalFunc tions();

// Get a MethodInfo for the PInvoke method
MethodInfo methodInfo = moduleBuilder.G etMethod(entryP ointName);

// Invoke the static method and return whatever it returns
ParameterInfo[] parameterInfo = methodInfo.GetP arameters();

Object returnValue = new Object();

try
{
methodInfo.Invo ke(null, parameterValues );
MessageBox.Show (String.Format( "Value calculated: {0}",
parameterValues[2]));
Jan 9 '06 #1
1 2331

"Marek" <no*****@dnv.co m> wrote in message
news:OM******** ******@TK2MSFTN GP11.phx.gbl...
| Hi
| I need to call a native function in a C++ dll from my C#. The C++
function
| declaration is shown below.
|
| The C# code that I have been trying to perform the call is also shown
below.
| All it is trying to do is to pass in two integers, add them together and
| return the result in the third parameter (byref/as a pointer).
|
| The problem is how do I specify the third parameter to be a pointer to
type
| int?
|
| Thanks for any help in advance.
|
| Marek
|
| C++ function declaration
|
=============== =============== =============== =============== =============== =====
| extern "C"
| {
| __declspec( dllexport ) void WINAPI SumIntWithRef(i nt a, int b, int* pc)
| {
| *pc = a + b;
| }
| }
|
| C# call
|
=============== =============== =============== =============== =============== =============== ==
|
| string dllName = @"NativeFunctio nDLL.dll";
| string entryPointName = "SumIntWithRef" ;
|
| //...Set up the return value:
| Type returnType = null;
|
| //...Set up the parameters:
| Type[] parameterTypes = new Type[3];
| object[] parameterValues = new object[3];
|
| parameterTypes[0] = typeof(int);
| parameterValues[0] = 2;
|
| parameterTypes[1] = typeof(int);
| parameterValues[1] = 3;
|
| parameterTypes[2] = typeof(int); //...How should this one be
| specified?
| parameterValues[2] = 0;
|
| // Create a dynamic assembly and a dynamic module
| AssemblyName assemblyName = new AssemblyName();
| assemblyName.Na me = "tempDll";
| AssemblyBuilder assemblyBuilder =
| AppDomain.Curre ntDomain.Define DynamicAssembly (assemblyName,
| AssemblyBuilder Access.Run);
| ModuleBuilder moduleBuilder =
| assemblyBuilder .DefineDynamicM odule("tempModu le");
|
| // Dynamically construct a global PInvoke signature
| // using the input information
| MethodBuilder methodBuilder =
| moduleBuilder.D efinePInvokeMet hod(entryPointN ame,
|
dllName,
|
MethodAttribute s.Static
|| MethodAttribute s.Public | MethodAttribute s.PinvokeImpl,
|
CallingConventi ons.Standard,
|
returnType,
|
parameterTypes,
|
CallingConventi on.Winapi,
|
CharSet.Ansi);
|
| //...This global method is now complete:
|
methodBuilder.S etImplementatio nFlags(MethodIm plAttributes.Pr eserveSig);
| moduleBuilder.C reateGlobalFunc tions();
|
| // Get a MethodInfo for the PInvoke method
| MethodInfo methodInfo =
moduleBuilder.G etMethod(entryP ointName);
|
| // Invoke the static method and return whatever it returns
| ParameterInfo[] parameterInfo = methodInfo.GetP arameters();
|
| Object returnValue = new Object();
|
| try
| {
| methodInfo.Invo ke(null, parameterValues );
| MessageBox.Show (String.Format( "Value calculated: {0}",
| parameterValues[2]));
|
|

Use the DefinePInvokeMe thod overload that takes a
parameterTypeRe quiredCustomMod ifiers and set IsByRef for the third argument.

Willy.
Jan 9 '06 #2

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

Similar topics

10
4287
by: Michael | last post by:
Guys, I'm interested in how the compiler implements function calls, can anyone correct my understanding/point me towards some good articles. When a function is called, is the stack pointer incremented by the size of the variables declared in the called function, and then the function will know where these are in memory relative to the current stack pointer position. ALso how are variables returned, is that by a set position in the...
2
2320
by: Martin Zenkel | last post by:
Dear VS Team, using the Beta 2 of VS 2005 I've encontered the following problem. Let's assume threre are three Dll's, one unmanaged and two managed. In the unmanaged we put a simple unmanged struct "A" which is exported in the usual way. The first managed assembly defines a managed class "B" using the unmanaged class "A" defined in the unmanaged Dll. This class "B" has got a public
1
2601
by: H.B. | last post by:
Hi, I need to make a function that can display data on my Managed C++ app and be called by an unmanaged C++ DLL. Something like : void Form1::Form1_Load(System::Object * sender, System::EventArgs * e) { MyDLLInit(MyAppDisplayFunction); }
14
2559
by: Mike Labosh | last post by:
How do you define whether the return value of a function is ByRef or ByVal? I have a utility class that cleans imported records by doing *really heavy* string manipulation in lots of different methods, and it operates on DataTables in excess of 100,000 rows of anywhere between 4 and 30 columns. I'd like to get the functions to return ByRef for greater speed and memory efficiency, but I can't see how to do that. --
3
8565
by: Vinz | last post by:
Hello everyone, With no C# nor C++ experience I wanted to make a C# WinForms client calling a C++ Win32 DLL. All day long I have been scraping knowledge from webpages and the C++ pocketreference from O'Reilly and I now have something working! I'm using Visual Studio 2005 for both programs and I'd just like to hear comments on the (very little) code I'm about to show and also I have a few questions if you don't mind...
27
3119
by: Terry | last post by:
I am getting the following warning for the below function. I understand what it means but how do I handle a null reference? Then how do I pass the resulting value? Regards Warning 1 Function 'Dec2hms' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
5
2074
by: Fei Liu | last post by:
Hello, I just hit a strange problem regarding SFINAE. The following code causes compile error (void cannot be array element type), I thought SFINA should match test(...) version instead and not issue any error. If I replace U with U(*), then the code compiles again. I couldn't make the sense out of it. What's the magic with (*)? Note that function<int>::yes returns correct result 0 even with U. Please help me out.
1
11291
by: obiwanjacobi | last post by:
Hi there, This is probably a really dump question but I'm stuck and need a leg- up with this. I'm writing a C++ interop layer that couples a managed plugin to an unmanaged host (specifically its a managed implementation for a Virtual Studio Technology -VST- plugin). So I'm writing a thin C++ layer that does little more than marshal calls to the managed layer. In this scenario I need to call a managed method with an out parameter
1
3138
by: giovannino | last post by:
Dear all, I did a query which update a sequence number (column NR_SEQUENZA) in a table using a nice code (from Trevor !). 1) Given that I'm not a programmer I can't understand why numbering doesn't start always, running more times the update query, from the same starting parameter assigned (1000000000). It seems to me that it takes memory last number calculated and running prox update it starts from last table row updated. I need...
0
8638
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
8578
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
9120
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...
0
8998
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
8857
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
7668
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
4346
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...
0
4586
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3013
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.