How to reuse a .Net assembly from a pure C application
I have a legacy application writte开发者_运维百科n in C , and i would like to gradually move some code to c#. But before being able to rewrite everything i will need to have just few components writen in c# first that are going to be used from C.
I assume your C# class is a static class. You need to create an interop layer in C++/CLI before you can use it in pure C. Create a C++/CLI class to wrap your C# class. Once that is done use the export function to export the specific C functions. C++/CLI will manage the interop on your behalf. The rule of thumb is if you class/function has any CLI it WILL BE CLI. So your extern functions should only return native datatypes.
extern "C" __declspec( dllexport ) int MyFunc(long parm1);
Here is an article to help you get started. It converts C++ to C# but the process is reversed in your case. CodeProject Unfortunately there is no convenient reverse PInvoke for pure C.
Unfortunately I have never gone from C# to C. It sounds like an interesting project. Good luck!
Ok If you have not figured it out yet i have a quick sample for you.
C# CSLibrary.Math.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSLibrary
{
static public class Math
{
static public int Add(int a, int b)
{
int c = a + b;
return c;
}
}
}
Cpp/C++ Project CPPCLibrary.h (Compiled with C++/CLI Option with project dependencies)
#pragma once
using namespace System;
extern "C" __declspec( dllexport ) int MathAdd(int a, int b)
{
return CSLibrary::Math::Add(a, b);
}
C Project CTest.c (Compiled as C Code)
#include "stdafx.h"
#pragma comment(lib, "../Debug/CPPCLILibrary.lib")
extern __declspec( dllimport ) int MathAdd(int a, int b);
int _tmain(int argc, _TCHAR* argv[])
{
int answer = MathAdd(10, 32);
_tprintf(_T("%d\n"), answer);
return 0;
}
All files are in the same solution but different projects. I have confirmed this has worked. I hope this helps anyone who comes across it.
Cheers!
If the code is pure C, you might be able to put it into a visual C++ assembly project without too much difficulty. From there, you would have access to a regular .net api.
精彩评论