473,837 Members | 1,473 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 2339

"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
4297
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
2331
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
2606
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
2572
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
8572
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
3138
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
2081
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
11345
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
3150
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
9842
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
10566
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...
0
10271
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
9398
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
7000
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
5848
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4474
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
2
4040
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3124
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.