简体   繁体   English

如何在 C 应用程序中使用 C# DLL?

[英]How to use a C# DLL in a C application?

I have C# DLL and I am using that DLL in C++ with the help of COM Interop by importing the corresponding .tlb file in my .cpp file #import "com.MyIntrop.tlb" and its working absolutely fine.我有 C# DLL,我在 COM Interop 的帮助下在 C++ 中使用该 DLL,方法是在我的.cpp文件中导入相应的.tlb文件#import "com.MyIntrop.tlb"并且它的工作非常好。

Now I want to use same DLL in my C code but because I can not use #import in C how to use same DLL which I have register as COM assembly in C.现在我想在我的 C 代码中使用相同的 DLL,但是因为我不能在 C 中使用#import如何使用我在 C 中注册为 COM 程序集的相同 DLL。

Here is a simple example with 3 files这是一个包含 3 个文件的简单示例

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

First the C# DLL.首先是 C# DLL。 This will be built as a 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";
      }
   }
}

Now the interface program.现在是界面程序。 This is the glue logic.这就是胶水逻辑。 This has to be compiled as C++/CLR but can be in the same project as main: just not in the same file as it has to be compiled differently.这必须编译为 C++/CLR,但可以与 main 在同一个项目中:只是不在同一个文件中,因为它必须以不同的方式编译。 Under General in Common Language Runtime Support, select Common Language Runtime Support (/clr) .常规的公共语言运行库支持,选择公共语言运行库支持(/ 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);
}

Now the main program.现在是主程序。

#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;
}

Set the dependency to the DLL.将依赖项设置为 DLL。 Set the build platform to Mixed Platforms not win32 or any CPU.将构建平台设置为混合平台,而不是 win32 或任何 CPU。 If it is set to any of those, something won't build.如果将其设置为其中任何一个,则不会构建某些内容。 Run it and you will get运行它,你会得到

Value is 42
String value is Hey it works

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM