Mixing unmanaged C ++ and CSHARP

Source: Internet
Author: User

Because the new project will mainly use CSHARP and will also involve mix programming problems, and native C ++ and C ++ CLI (Common Language infrastructure), today's quick Google, do some preliminary understanding first.

Current understanding:

1. The mix programming mentioned here should mean that CSHARP modules, native C ++ modules, and C ++ CLI modules can call each other. Of course, the code in different languages is not written together directly ..

2. The methods used by CSHARP's module to use native C ++ module are known to be:

A. Use C ++ CLI to package the native C ++ module into a wrapper module. Then, let the CSHARP module call this wrapper. In addition, through makefile, you can also package modules written in different languages into an EXE!

B. directly use the C # syntax + native C ++ to export functions (the general idea of calling C ++ functions in C # code is as follows: first, write the C ++ function as a dll library, and then import the function in the DLL in C # For calling ).

1. The approximate format is as follows:

    C ++ code:

1 int staticelementnumber = 10;

2 extern "C" afx_api_export int getarrayelementnumber ()

3 {

4 return staticelementnumber;

5}

    C # code:
(Import the function, which is written in the class where the function is called)

1 [dllimport ("mfcdll. dll")]

2 public static extern int getarrayelementnumber ();

3 int elementnumber = getarrayelementnumber ();

2. because of the different data types in these two languages, the same fucntion interface cannot be achieved when native C ++'s export function is used. However, with the help of CLR, the following types can be effectively handled:

      A. (C ++) extern "C" afx_api_export hbitmap getabitmap (wchar * strfilename) =>

(CSHARP) public static extern intptr getabitmap ([financialas (unmanagedtype. lpwstr)] string strfilename );

B. (C ++) extern "C" afx_api_export bool getarray (INT elementnumber, double * baseaddress) =>

(CSHARP) public static extern bool getarray (INT elementnumber, [financialas (unmanagedtype. lparray, sizeparamindex = 0)] Double [] baseaddress );

    3. C # In the setting project, you can set whether to debug unmanaged code debugging. In this case, when running the CSHARP module, debug directly into the C ++ module!

3.System.Runtime.InteropServices.Marshal

4. repost a q & A (http://bytes.com/topic/c-sharp/answers/715638-mixing-unmanaged-c-c)

Mixing unmanaged C ++ and C #

Jon slaughter guest   Posts: N/A #1: SEP 29' 07
How difficult is it for one to integrate unmanaged C ++ into C #? I know
Functions one can use dllimport but how does one go about doing it
Classes? Do I have to completely reimplement the classes in managed C ++ as
Wrapper to the unmanaged C ++ classes or is there an easier way?

Essential tially what I have done is written a C ++ Kernel Mode driver and I want
To use it from my C # program. Because it requires some setup outside
Kernel (because it has to pass buffers back and forth and extract
Information out of the buffers) I 'd rather keep the specific code
Unmanaged because its probably slightly faster.

But I don't want to have a huge number of DLL imports and write a C # wrapper
Class over each of the imports because it seems a little excessive. (Not
Only does the driver internally use a similar class but I 'd essential be
Implementing the same class 3 times... one in the driver, which is actually
Slightly different but pretty much with same interface, one in unmanaged C ++
To interface with the driver, and some type of managed wrapper .)

Is there a better way? Can I just mix unmanaged and managed C ++ in the same
Project to do all the work and not have to end up with a C # wrapper?
Basically I think I can get away with just using unsafe code to work
The buffers. I'm mainly worried about the performance hit associated
Doing this. From my initial tests C # Is anywhere from 2-5 times slower
Calling kernel mode drivers than unmanaged C ++ (not sure if I can get any
Speed up by indirectly referencing unamanged C ++ though so I might take that
Hit no matter what if I plan on using C #). Of course I don't want to end up
With having to change 3 classes every time I make a simple change either.

Any ideas?

Thanks,
Jon

C ++ to C # ConverterMost accurate C ++ to C # converter. Free demo, support, & updates.

Www.tangiblesoftwaresolutions.com

Willy denoyette [MVP] Guest   Posts: N/A #2: SEP 29' 07
Re: mixing unmanaged C ++ and C # "Jon slaughter" <Jon_Slaughter@Hotmail.comwrote in message
News: a4kli. 55678 $ YL5.43177@newssvr29.news.prodigy. net...

Quote:

How difficult is it for one to integrate unmanaged C ++ into C #? I know
Functions one can use dllimport but how does one go about doing it
Classes? Do I have to completely reimplement the classes in managed C ++
A wrapper to the unmanaged C ++ classes or is there an easier way?
>

C ++ classes cannot be used directly from C #, only pure C functions can be
Called through the pinvoke layer.
The only way you can create instances of unmanaged C ++ is by wrapping these
Classes by a Managed class that delegates the operations on the unmanaged
Class. Quote:

Essential tially what I have done is written a C ++ Kernel Mode driver and I
Want to use it from my C # program. Because it requires some setup outside
The kernel (because it has to pass buffers back and forth and extract
Information out of the buffers) I 'd rather keep the specific code
Unmanaged because its probably slightly faster.
>

Not necessarely, keep in mind that you are adding a layer and as such you
Are extending the path to the final code.
. Quote:

But I don't want to have a huge number of DLL imports and write a C #
Wrapper class over each of the imports because it seems a little
Excessive. (not only does the driver internally use a similar class
I 'd essential be implementing the same class 3 times... one in
Driver, which is actually slightly different but pretty much with same
Interface, one in unmanaged C ++ to interface with the driver, and some
Type of managed wrapper .)
>
Is there a better way? Can I just mix unmanaged and managed C ++ in
Same project to do all the work and not have to end up with a C # wrapper?

Yep, you can have the wrapper and the native code in one project, even in
The same Assembly. c ++/CLI can mix native and managed code in a single DLL. Quote:

Basically I think I can get away with just using unsafe code to work
The buffers. I'm mainly worried about the performance hit associated
Doing this. From my initial tests C # Is anywhere from 2-5 times slower
Calling kernel mode drivers than unmanaged C ++ (not sure if I can get any
Speed up by indirectly referencing unamanged C ++ though so I might take
That hit no matter what if I plan on using C #). Of course I don't want
End up with having to change 3 classes every time I make a simple change
Either.
>

2-5 times? How did you compile the CS module, how did you declare
Pinvoke signature (dllimport), what function are you actually calling, what
Are you measuring and how did you measure this?

The first time you call into unmanaged from managed you'll incur a serious
Call overhead, this is because the CLR has to synthesize and JIT
(Encryption aling) thunk, but once the Thunk is created the overhead is very low,
All depends on the argument types, the number of arguments and the security
Attribute Set on the invoked function.
For instance, calling a function that takes no or only blittable type
Arguments and which has the suppressunmanagedcodesecurity attribute set [1],
The overhead is only 4 instructions. This is the minimal overhead taken
Signal the GC that the thread has transitioned into unmanaged or returned
From unmanaged.
Functions that take arrays or structures of BITs-able types only, take
Overhead ~ 50 instructions, while functions that take string arguments
[3], incur the highest overhead 50-xxx instructions depending on the Type
Unmanaged char (wide Char or MBCS), the reason for this is that
Extends ALER needs to convert the managed string representation into
Unmanaged Char or wchar_t representation.

[1] 4 instructions overhead
[Dllimport ("Lib. dll"), suppressunmanagedcodesecurity] extern static int
F (int I );

[2] ~ 50 instructions overhead
[Dllimport ("Lib. dll"), suppressunmanagedcodesecurity] extern static void
F (INT [] IA );

[3] ~ 55 instructions overhead
[Dllimport ("Lib. dll"), suppressunmanagedcodesecurity] extern static int
FS ([financialas (unmanagedtype. lpwstr)] string S );
Extern "C" _ declspec (dllexport) int _ stdcall FS (wchar_t * s ){....}

A minimum of several hundred instruction depending on the string length.
[Dllimport ("Lib. dll"), suppressunmanagedcodesecurity] extern static int
FS (string S );
Extern "C" _ declspec (dllexport) int _ stdcall FS (char * s ){....}

The managed/unmanaged transition is low when compared to a kernel transition
(+ 4000 instruction), add to that you will probably execute several
Thousands instruction in the driver, and it becomes apparent that
Managed/unmanaged overhead becomes negligible. After all, this is
Overhead the you'll take when using the IO, socket etc... classes from
Managed code. configurming disk IO from managed code is not measurable slower
Than from unmanaged code.

Willy.

Leon Lambert guest   Posts: N/A #3: Oct 1' 07
Re: mixing unmanaged C ++ and C # I wocould write a wrapper assembly in managed C ++ using ijw (it just
Works). Following is a link to a code project sample that shows how easy
It is to mix managed and unmanaged C ++ I used it and it works great.
Http://www.codeproject.com/managedcpp/ijw_unmanaged.asp

Hope it works for you.
Leon Lambert

Similar C #/C sharp bytes

  • This is probably a Noobie question:

    I just created a new C ++/CLI project in VS 2005. It created an empty
    Class:

    Public ref class... "href =" http://bytes.com/topic/net/answers/671265-c-cli-mixing-managed-unmanaged "target =" _ blank "> C ++/CLI mixing managed/unmanaged (ANSWERS)

  • I have problem mixing managed and unmanaged C ++ code in. NET 2003. I want to create a Windows Forms application which uses some C ++ code... "href =" http://bytes.com/topic/net/answers/404043-mixing-managed-unmanaged-code "target =" _ blank "> mixing managed and unmanaged code (ANSWERS)
  • My question is (see example below ):
    1) Is it a bug that the... "href =" http://bytes.com/topic/net/answers/281518-mixing-mananged-unmanaged-unmanaged-class "target =" _ blank "> mixing mananged and unmanaged in an unmanaged class (ANSWERS)
  • I have problem mixing managed and unmanaged C ++ code in. NET 2003. I want to create a Windows Forms application which uses some C ++ code... "href =" http://bytes.com/topic/net/answers/112091-mixing-managed-unmanaged-code "target =" _ blank "> mixing managed and unmanaged code (ANSWERS)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.