在c ++项目中调用c#dll或类 [英] call c# dll or class within c++ project

查看:77
本文介绍了在c ++项目中调用c#dll或类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发c ++应用程序。现在我想在c ++程序中调用c#中的一个类。这有什么办法吗?是否可以将c#程序作为Web服务并向c ++项目添加服务引用。

I am developing c++ application. Now i want to call a class in c# within the c++ program. is there any way to this? Is it possible to make the c# program as web service and add service reference to the c++ project.

推荐答案

如果使用COM,则可以。你应该让你的C#类暴露给COM,然后你可以在C ++中使用它。以下是一个问题的例子:



It is possible if you use COM. You should make your C# class exposed to COM and then you can use it in C++. Here is an example inspired by a question here:

namespace ManagedDLL
{
   // Interface declaration.
   [Guid("32529FAE-6137-4c62-9945-DE4198FA9D1B")]
   [InterfaceType(ComInterfaceType.InterfaceIsDual)]
   public interface ICalculator
   {
      [DispId(1)]
      int Add(int Number1, int Number2);
   };
}







namespace ManagedDLL
{
   // Interface implementation.
   [Guid("9F2F180D-94A9-47e6-91CC-6BCFABD1DDEB")]
   [ClassInterface(ClassInterfaceType.None)]
   [ProgId("ManagedDLL.ManagedClass")]
   public class ManagedClass : ICalculator
   {
      public int Add(int Number1, int Number2)
      {
         return Number1 + Number2;
      }
   }
}





然后你可以在C ++中使用它:





Then you can use this in C++:

#import "..\bin\ManagedDLL.tlb" raw_interfaces_only
using namespace ManagedDLL;

int _tmain(int argc, _TCHAR* argv[])
{
   // Initialize COM.
   HRESULT hr = CoInitialize(NULL);

   // Create the interface pointer.
   ICalculatorPtr pICalc(__uuidof(ManagedClass));

   long lResult = 0;

   // Call the Add method.
   pICalc->Add(5, 10, &lResult);

   wprintf(L"The result is %d\n", lResult);


   // Uninitialize COM.
   CoUninitialize();

   return 0;
}


无需将其设为网络服务。使用C ++ / CLI,您可以在C ++程序中实例化C#的类,就像C ++类一样。您需要使用gcnew(而不是new)来实例化.NET类。



有关详细信息,请参阅:

http://en.wikipedia.org/wiki/C%2B%2B/CLI [ ^ ]
No need to make it a web service. Using C++/CLI you can instantiate your C#'s class in your C++ program almost like C++ classes. You need to use gcnew (instead of new) to instantiate .NET classes.

For details, see:
http://en.wikipedia.org/wiki/C%2B%2B/CLI[^]


使用CLR托管API

请参阅:

http: //msdn.microsoft.com/en-us/magazine/cc163567.aspx [ ^ ]

http:/ /code.msdn.microsoft.com/windowsdesktop/CppHostCLR-e6581ee0 [ ^ ]
Use CLR Hosting APIs
see this:
http://msdn.microsoft.com/en-us/magazine/cc163567.aspx[^]
http://code.msdn.microsoft.com/windowsdesktop/CppHostCLR-e6581ee0[^]


这篇关于在c ++项目中调用c#dll或类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆