我用C编写的遗留应用程序,我想逐步将一些code到C#。但能够改写一切之前,我需要有writen在C#中:第一,要在C中使用的只是很少部分。
I have a legacy application written 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.
我假设您的 C#类是一个静态类。您需要创建在互操作层的 C ++ / CLI 之前,你可以用它在纯的 C 。创建一个 C ++ / CLI 类来包装您的 C#类。一旦做到这一点使用导出功能导出的特定的 C 功能。 C ++ / CLI会负责替你的互操作。经验法则是,如果你的类/函数有任何CLI将被CLI。所以,你的extern函数应该只返回原始数据类型。
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);
下面是一篇文章,以帮助您开始。它把 C ++ 为 C#,但该方法是在你的情况下逆转。 $ C $的CProject 不幸的是,没有方便的反向的PInvoke 作为纯粹的 C
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.
不幸的是我从来没有经历了从 C#为 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 ++项目CPPCLibrary.h (编译与C ++ / CLI选项的项目依赖)
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 ++项目CTest.c (编译为C code)
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.
干杯!