Click here to Skip to main content
15,891,473 members
Articles / Desktop Programming / Win32

Mixing .NET and native code

Rate me:
Please Sign up or sign in to vote.
4.85/5 (49 votes)
7 Apr 2014CPOL9 min read 164K   7.2K   140  
A first approach to mixing .NET and native code, using the C++/CLI gateway.
// AdR.Samples.CLRCallingNative.MixedDLL.h

#pragma once

using namespace System;
using namespace System::Runtime::InteropServices;


namespace AdR {
   namespace Samples {
      namespace CLRCallingNative {
         namespace MixedDLL {

public ref class Person
{
public:
   Person(String^ name, DateTime birthDate);
   virtual ~Person();

   property unsigned int Age
   {
      unsigned int get();
   }

   static int CallCFunctionImplicit();
   static int CallCVarImplicit();

   // Sample of direct native API call.
   [DllImport("AdR.Samples.CLRCallingNative.NativeDLL.dll")]
   static int fnNativeDLL();

   // Note that direct call of a variable export is forbidden.

private:
   Person() : _pPerson(NULL) { }

   // NOTE: Declaring a member "CPerson _person2;" would generate a C4368 compiler error
   //       (cannot define 'member' as a member of managed 'type': mixed types are not supported).
   //
   // That's why a pointer (seen as 'unsafe' in C#) is created.
   //
   // What says the documentation:
   // ----------------------------
   // You cannot embed a native data member in a CLR type.
   //
   // You can, however, declare a pointer to a native type and control its lifetime in the
   // constructor and destructor and finalizer of your managed class (see Destructors and Finalizers
   // in Visual C++ for more information).
   CPerson* _pPerson;
};

} } } }

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
France France
I started working in 1991 as an engineer. My pecialization: development in robotics.

After two years in this job, I began a new career leaving robotics, and coming to standard development as C++ expert.

This enabled me to diversify my knowledge by putting one foot on the side of the systems. Then began my double competence.

In 2000 I started a new job as consultant. Many experiences came with that new job, continuing with both development and systems subjects.

I reinforced my knowledge in technical architectures, IT security, and IT production management.

2011: a new experience. I founded the company Net-InB, a computer services company specialized in the fields of infrastructures, systems and software.

Now I am both technical and software architect specialized in Microsoft products and technologies.

Comments and Discussions