【问题标题】:How to use a C# DLL in a C application?如何在 C 应用程序中使用 C# DLL?
【发布时间】:2014-01-27 18:12:35
【问题描述】:

我有 C# DLL,我在 COM Interop 的帮助下在 C++ 中使用该 DLL,方法是在我的 .cpp 文件 #import "com.MyIntrop.tlb" 中导入相应的 .tlb 文件,并且它工作得非常好。

现在我想在我的 C 代码中使用相同的 DLL,但是因为我不能在 C 中使用 #import 如何使用我在 C 中注册为 COM 程序集的相同 DLL。

【问题讨论】:

  • 问题出在哪里?只需从 IDL 中获取一个头文件。
  • 同样的方式你会在 C 中使用任何 COM 对象 here 一个非常小的例子。
  • 谷歌搜索了一些答案,也许这个答案会有所帮助。 stackoverflow.com/questions/728325/…
  • 根据过去的经验,我建议您在 C 中重新编码函数或迁移到 C#。多年前,我花了很多时间试图让我的 C 代码调用托管代码。我让它工作了,但几年后,随着大量的变化,对托管 dll 的调用表单 C 中断了,我似乎不记得我之前做了什么让它工作。从内存中,您需要 1) 具有 COMVisible 属性,2) 使用强命名程序集,3) 生成 .tlb 文件,4) 将 dll 添加到 GAC,5) 使用 regsvr 注册 .tlb
  • 顺便说一句,我们最终用 c# 重写,以便其他开发人员可以维护它

标签: c# c++ c


【解决方案1】:

这是一个包含 3 个文件的简单示例

  1. C# 中的 DLL
  2. C++/CLR 中的接口程序
  3. C++ 主程序

首先是 C# DLL。这将被构建为 DLL。

using System;
using System.Collections.Generic;
using System.Text;

namespace csdll
{
   public class ReturnValues
   {
      public void CSGetInt(ref int x)
      {
         x = 42;
      }

      public void CSGetStr(ref string s)
      {
         s = "Hey it works";
      }
   }
}

现在是界面程序。这就是胶合逻辑。这必须编译为 C++/CLR,但可以与 main 在同一个项目中:只是不能在同一个文件中,因为它必须以不同方式编译。在 Common Language Runtime Support 的 General 下,选择 Common Language Runtime Support (/clr)

#include <string>
#include <msclr\marshal_cppstd.h>
#using "csdll.dll"
using namespace System;

extern void cppGetInt(int* value)
{
   csdll::ReturnValues^ rv = gcnew csdll::ReturnValues();
   rv->CSGetInt(*value);
}

extern void cppGetStr(std::string& value)
{
   System::String^ csvalue;
   csdll::ReturnValues^ rv = gcnew csdll::ReturnValues();
   rv->CSGetStr(csvalue);
   value = msclr::interop::marshal_as<std::string>(csvalue);
}

现在是主程序。

#include "stdafx.h"
#include <iostream>
#include <string>

// These can go in a header
extern void cppGetInt(int* value);
extern void cppGetStr(std::string& value);

int _tmain(int argc, _TCHAR* argv[])
{
   int value = 99;
   std::string svalue = "It does not work";
   cppGetInt(&value);
   std::cout << "Value is " << value << std::endl;
   cppGetStr(svalue);
   std::cout << "String value is " << svalue << std::endl;
   return 0;
}

设置对 DLL 的依赖。 将构建平台设置为 混合平台 而不是 win32 或任何 CPU。如果将其设置为其中任何一个,则将无法构建某些东西。运行它,你会得到

Value is 42
String value is Hey it works

【讨论】:

    猜你喜欢
    • 2010-10-08
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多