473,785 Members | 3,245 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Calling C++ function pointer from C#

I have a c++ code that callls csharp. Now I want to be able to pass
a function pointer from C++ to Csharp code and have c# callback to it.
Is it possible and how?

Here is what I have so far :
#include "windows.h"
#include <stdio.h>
#import "CSDll.tlb" named_guids

int main(int argc, char* argv[])
{
HRESULT hRes = S_OK;
CoInitialize(NU LL);
CSDll::IMyManag edInterface *pManagedInterf ace = NULL;

hRes = CoCreateInstanc e(CSDll::CLSID_ Class1, NULL,
CLSCTX_INPROC_S ERVER,
CSDll::IID_IMyM anagedInterface , reinterpret_cas t<void**>
(&pManagedInter face));

if (S_OK == hRes)
{
hRes = pManagedInterfa ce->raw_Run();
pManagedInterfa ce->Release();
}

CoUninitialize( );
return 0;
}
Nov 19 '08 #1
6 8545
sasha wrote:
I have a c++ code that callls csharp. Now I want to be able to pass
a function pointer from C++ to Csharp code and have c# callback to it.
Is it possible and how?
Do you have a special reason for using COM interop instead of C++ interop?
With C++ interop, you can create a delegate in C++/CLI and pass it to the C#
code.
>
Here is what I have so far :
#include "windows.h"
#include <stdio.h>
#import "CSDll.tlb" named_guids

int main(int argc, char* argv[])
{
HRESULT hRes = S_OK;
CoInitialize(NU LL);
CSDll::IMyManag edInterface *pManagedInterf ace = NULL;

hRes = CoCreateInstanc e(CSDll::CLSID_ Class1, NULL,
CLSCTX_INPROC_S ERVER,
CSDll::IID_IMyM anagedInterface , reinterpret_cas t<void**>
(&pManagedInter face));

if (S_OK == hRes)
{
hRes = pManagedInterfa ce->raw_Run();
pManagedInterfa ce->Release();
}

CoUninitialize( );
return 0;
}

Nov 19 '08 #2
On Nov 19, 9:54*am, "Ben Voigt [C++ MVP]" <r...@nospam.no spamwrote:
sasha wrote:
I have a c++ code that *callls csharp. Now I want to be able to pass
a function pointer from C++ to Csharp code and have c# callback to it.
Is it possible and how?

Do you have a special reason for using COM interop instead of C++ interop?
With C++ interop, you can create a delegate in C++/CLI and pass it to theC#
code.
Here is what I have so far :
#include "windows.h"
#include <stdio.h>
#import "CSDll.tlb" named_guids
int main(int argc, char* argv[])
{
* *HRESULT hRes = S_OK;
* *CoInitialize(N ULL);
* *CSDll::IMyMana gedInterface *pManagedInterf ace = NULL;
* *hRes = CoCreateInstanc e(CSDll::CLSID_ Class1, NULL,
CLSCTX_INPROC_S ERVER,
* * CSDll::IID_IMyM anagedInterface , reinterpret_cas t<void**>
(&pManagedInter face));
* *if (S_OK == hRes)
* *{
* * * *hRes = pManagedInterfa ce->raw_Run();
* * * *pManagedInterf ace->Release();
* *}
* * CoUninitialize( );
return 0;
* }
I have no reason, frankly speaking. How would I do that. please
provide the reference to it. I have lots of legacy code, as a back-
end, that heavily relies on function pointers. And I want to call
those from my C# code. Any suggestion or examples of that?

Thanks
Nov 19 '08 #3
You have 3 options:

Using Explicit PInvoke in C++ (DllImport Attribute)

Using C++ Interop (Implicit PInvoke)

A Closer Look at Platform Invoke

Read more here: http://msdn.microsoft.com/en-us/libr...82(VS.80).aspx
"sasha" <ab*********@gm ail.comwrote in message
news:ce******** *************** ***********@v16 g2000prc.google groups.com...
On Nov 19, 9:54 am, "Ben Voigt [C++ MVP]" <r...@nospam.no spamwrote:
sasha wrote:
I have a c++ code that callls csharp. Now I want to be able to pass
a function pointer from C++ to Csharp code and have c# callback to it.
Is it possible and how?

Do you have a special reason for using COM interop instead of C++ interop?
With C++ interop, you can create a delegate in C++/CLI and pass it to the
C#
code.
Here is what I have so far :
#include "windows.h"
#include <stdio.h>
#import "CSDll.tlb" named_guids
int main(int argc, char* argv[])
{
HRESULT hRes = S_OK;
CoInitialize(NU LL);
CSDll::IMyManag edInterface *pManagedInterf ace = NULL;
hRes = CoCreateInstanc e(CSDll::CLSID_ Class1, NULL,
CLSCTX_INPROC_S ERVER,
CSDll::IID_IMyM anagedInterface , reinterpret_cas t<void**>
(&pManagedInter face));
if (S_OK == hRes)
{
hRes = pManagedInterfa ce->raw_Run();
pManagedInterfa ce->Release();
}
CoUninitialize( );
return 0;
}
I have no reason, frankly speaking. How would I do that. please
provide the reference to it. I have lots of legacy code, as a back-
end, that heavily relies on function pointers. And I want to call
those from my C# code. Any suggestion or examples of that?

Thanks

Nov 19 '08 #4
sasha wrote:
On Nov 19, 9:54 am, "Ben Voigt [C++ MVP]" <r...@nospam.no spamwrote:
>sasha wrote:
>>I have a c++ code that callls csharp. Now I want to be able to pass
a function pointer from C++ to Csharp code and have c# callback to
it. Is it possible and how?

Do you have a special reason for using COM interop instead of C++
interop? With C++ interop, you can create a delegate in C++/CLI and
pass it to the C# code.
[snip]
I have no reason, frankly speaking. How would I do that. please
provide the reference to it. I have lots of legacy code, as a back-
end, that heavily relies on function pointers. And I want to call
those from my C# code. Any suggestion or examples of that?

Thanks
Well that's actually a slightly different problem. There's
System::Runtime ::InteropServic es::Marshal::Ge tFunctionPointe rForDelegate
that helps with that in p/invoke. And it seems there's
GetDelegateForF unctionPointer for the case you originally mentioned.

For C++ interop, you don't have to do anything special at all. You just
compile your code with C++/CLI and call your legacy code normally. If you
want a C++/CLI function to be usable by C#, put it into a "ref class".

trivial example:

#include <cmath>
ref class Wrapper // ref class, C# can use it
{
public:
static double ComputeIt()
{
return System::Math::S in(0.2) + std::sin(0.3); //
see, it can both call C# and legacy C++ code in the same function
}
};
Nov 19 '08 #5
On Nov 19, 4:55 pm, "Ben Voigt [C++ MVP]" <r...@nospam.no spamwrote:
sasha wrote:
On Nov 19, 9:54 am, "Ben Voigt [C++ MVP]" <r...@nospam.no spamwrote:
sasha wrote:
I have a c++ code that callls csharp. Now I want to be able to pass
a function pointer from C++ to Csharp code and have c# callback to
it. Is it possible and how?
Do you have a special reason for using COM interop instead of C++
interop? With C++ interop, you can create a delegate in C++/CLI and
pass it to the C# code.

[snip]
I have no reason, frankly speaking. How would I do that. please
provide the reference to it. I have lots of legacy code, as a back-
end, that heavily relies on function pointers. And I want to call
those from my C# code. Any suggestion or examples of that?
Thanks

Well that's actually a slightly different problem. There's
System::Runtime ::InteropServic es::Marshal::Ge tFunctionPointe rForDelegate
that helps with that in p/invoke. And it seems there's
GetDelegateForF unctionPointer for the case you originally mentioned.

For C++ interop, you don't have to do anything special at all. You just
compile your code with C++/CLI and call your legacy code normally. If you
want a C++/CLI function to be usable by C#, put it into a "ref class".

trivial example:

#include <cmath>
ref class Wrapper // ref class, C# can use it
{
public:
static double ComputeIt()
{
return System::Math::S in(0.2) + std::sin(0.3); //
see, it can both call C# and legacy C++ code in the same function
}

};

Wait, so from legacy code, I call managed c++ DLL, from the manage
DLL I call Csharp DLL.

is there an example of that as a starting point? thanks
Nov 20 '08 #6
sasha wrote:
On Nov 19, 4:55 pm, "Ben Voigt [C++ MVP]" <r...@nospam.no spamwrote:
>sasha wrote:
>>On Nov 19, 9:54 am, "Ben Voigt [C++ MVP]" <r...@nospam.no spam>
wrote:
sasha wrote:
I have a c++ code that callls csharp. Now I want to be able to
pass a function pointer from C++ to Csharp code and have c#
callback to it. Is it possible and how?
>>>Do you have a special reason for using COM interop instead of C++
interop? With C++ interop, you can create a delegate in C++/CLI and
pass it to the C# code.

[snip]
>>I have no reason, frankly speaking. How would I do that. please
provide the reference to it. I have lots of legacy code, as a back-
end, that heavily relies on function pointers. And I want to call
those from my C# code. Any suggestion or examples of that?
>>Thanks

Well that's actually a slightly different problem. There's
System::Runtim e::InteropServi ces::Marshal::G etFunctionPoint erForDelegate
that helps with that in p/invoke. And it seems there's
GetDelegateFor FunctionPointer for the case you originally mentioned.

For C++ interop, you don't have to do anything special at all. You
just compile your code with C++/CLI and call your legacy code
normally. If you want a C++/CLI function to be usable by C#, put it
into a "ref class".

trivial example:

#include <cmath>
ref class Wrapper // ref class, C# can use it
{
public:
static double ComputeIt()
{
return System::Math::S in(0.2) + std::sin(0.3);
// see, it can both call C# and legacy C++ code in the same function
}

};


Wait, so from legacy code, I call managed c++ DLL, from the manage
DLL I call Csharp DLL.

is there an example of that as a starting point? thanks
I just gave you an example. You need to make sure any managed libraries you
need to call are added as references, native libraries you use header files
and static libraries or import libraries as usual. There's nothing
special... throw a call to qsort into that example and the C++/CLI compiler
will automatically make the callback function pointer compatible with native
qsort. C++ interop is also called "It Just Works" :)

Unless I'm misunderstandin g your requirement. I think you want C# to call
C++/CLI, C++/CLI passes callback function pointers to legacy C++ libraries,
legacy C++ libraries calls through the function pointer back to C++/CLI
which can call other C++/CLI, legacy C++, C#, etc.
Nov 20 '08 #7

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

Similar topics

11
15793
by: Rajesh | last post by:
Dear All, Please let me know the advantage of function pointer? Is it fast calling function using function pointer? Is it possible to use function pointer to optimise code? Thanks and regards Rajesh
2
8291
by: David Rose | last post by:
I have a DLL (not .NET) that takes a function pointer argument and calls that function with an integer argument. The DLL is being called from C#. So far, it is partially working, but the integer argument is getting corrupted (MessageBoxes in the dll and C# fire). I do not understand why the int parameter is getting corrupted calling the callback function (Testing() in C#). ( probably I just don't understand
23
7818
by: bluejack | last post by:
Ahoy... before I go off scouring particular platforms for specialized answers, I thought I would see if there is a portable C answer to this question: I want a function pointer that, when called, can be a genuine no-op. Consider: typedef int(*polymorphic_func)(int param);
1
1227
by: Lloyd Dupont | last post by:
I have some managed C++ interacting with native DLL, for good integration I'm setting up some function pointer in the native DLL, passing some function pointer from the managed world. ================= typedef void __cdecl NSLogHandler(Oid exception); static void __cdecl ObjectiveNSLogHandler(Oid ns_str) { NSString^ str = dynamic_cast<NSString^>( ObjcRuntime::GetId(ns_str) ); Console::WriteLine("GNUstep.NET: "+str); }
5
11246
by: WittyGuy | last post by:
How to typecast a "function pointer" to "const void*" type in C++ way? int MyFunction (double money); // Function prototype const void* arg = (const void*)MyFunction; // type casting function pointer to const void* in C-style void(*pFunc)() = (void(*)())(arg); // type casting const void* to function pointer in C-style (*pFunc)(); // Calling the function after type casting is done
11
2742
by: Felix Kater | last post by:
Hi, I can compile and run this code (see below) which twice calls the function f, first with too less, second with too much arguments. But is it legal and free of memory leaks and other problems? Of course, I presume that inside f I don't access i in case it was called via g. int f(int i){ /* ... */ return 0; }
4
4178
by: Jonathan Green | last post by:
I have some questions about the behavior of the code below. #include <stdio.h> void test(void *v); int main(void) { int i=1; int j=2;
26
4886
by: aruna.mysore | last post by:
Hi all, I have a specific problem passing a function pointer array as a parameter to a function. I am trying to use a function which takes a function pointer array as an argument. I am too sure about the syntax of calling the same. #include <stdio.h> void fp1()
20
2246
by: MikeC | last post by:
Folks, I've been playing with C programs for 25 years (not professionally - self-taught), and although I've used function pointers before, I've never got my head around them enough to be able to think my way through what I want to do now. I don't know why - I'm fine with most other aspects of the language, but my brain goes numb when I'm reading about function pointers! I would like to have an array of structures, something like
4
4402
by: Immortal_Nephi | last post by:
I had a lot of research to see how function pointer works. Sometimes, programmers choose switch keyword and function in each case block can be called. Sometimes, they choose ordinary function pointer array instead of switch. They believe that ordinary function pointer is much faster than switch. Think of one variable called selectFunction. selectFunction variable can be the range of 0 through 1,000 or more. Load selectFunction...
0
9645
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
9480
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
10325
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
10091
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
6740
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
5381
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3646
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2879
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.