473,569 Members | 2,870 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 2324

"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
4276
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...
2
2312
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...
1
2592
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
2554
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...
3
8563
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...
27
3103
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
2065
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...
1
11256
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...
1
3119
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...
0
7605
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...
0
8118
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...
1
7665
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...
0
6277
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...
1
5501
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...
0
5217
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...
0
3631
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2105
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
1
1207
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.