user3174075 user3174075 - 1 year ago 125
C++ Question

How can I use C# code from a C++ DLL

I have a requirement that dictates use of an exported function from a C++ dll.

There is lots of stuff that needs to occur within the exported function, but I don't want to rewrite all of the C# code that I have written to do it.

I would like to just paste the C# code into the DLL and be done.

NOTE: I don't want to call a C# DLL, I want to put C# code INTO a C++ dll.

Here is the Exports.def file:

LIBRARY InstallCheckWin32
IsConnectionPointValid @1
fnTest @2

Here is my .h File for the DLL:

// The following ifdef block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the INSTALLCHECKWIN32_EXPORTS
// symbol defined on the command line. This symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// INSTALLCHECKWIN32_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
#define INSTALLCHECKWIN32_API __declspec(dllexport)
#define INSTALLCHECKWIN32_API __declspec(dllimport)


Here is the .cpp file:

// InstallCheckWin32.cpp : Defines the exported functions for the DLL application.

#include "stdafx.h"
#include "InstallCheckWin32.h"
#include <tchar.h>

// this is where I want to use C# objects
// eg:
DateTime now = DateTime.Now;

I have set the General Configuration Property "Common Language Runtime Support" to Common Language Runtime Support(/clr)

What else do I need to set to use C# code in a C++ dll?


Answer Source

No, you can't mix C# and C/C++ in same source file and expect compiler to somehow produce code for that.

In general mixing multiple coding languages in the same file has only limited support in some languages. With C/C++ you sometimes can mix assembly (as in mov ax,cx, not .Net assembly). Language/frameworks for site creation you frequently can mix in JavaScript (but not actually run at the same time)...

Fix: in most cases languages have comparable functionality/libraries - so it is frequently easier to rewrite code into one of the language. You can also interop between libraries written in different languages - how to do that depends on combination of languages. For some cases you can cross-compile source in one language to another, but generally it is limited to languages with same/similar frameworks (C++/C# is generally not falling into such bucket, but you still may find C# to C++ cross-compiler)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download