簡體   English   中英

如何將C ++ dll導入和使用/運行到另一個C#項目中?

[英]How to import and use/run a C++ dll into another C# project?

我創建了一個C#應用程序。 在此應用程序中,我想使用/運行另一個項目中的C ++ API(該API用宏編碼編寫)。 我嘗試導入該C ++項目的dll,並嘗試調用屬於該API的函數。 問題是它引發“無法找到方法”錯誤。

如何在C#項目中運行C ++項目?

您不能將本機DLL添加為對托管項目的引用。 您有3個主要選項:

  1. 通過p / invoke使本機函數可用。
  2. 通過COM公開本機代碼。
  3. 將本機代碼編譯為托管C ++程序集。

對於大量代碼,選項3是最有效和有效的方法。

如果“運行”是指一個單獨的過程:

使用.NET中可用的類System.Diagnostics.Process

myProcess.StartInfo.FileName = "notepad.exe";
myProcess.StartInfo.CreateNoWindow = false;
myProcess.Start();

否則,如果您要使用C ++開發的dll,則可以使用Platform Invoke Services

using System;
using System.Runtime.InteropServices;

class PlatformInvokeTest
{
    //First param is of course either in your PATH, or an absolute path:
    [DllImport("msvcrt.dll", EntryPoint="puts", CallingConvention=CallingConvention.Cdecl)]
    public static extern int PutString(string c);
    [DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)]
    internal static extern int _flushall();

    public static void Main() 
    {
        PutString("Test");
        _flushall();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM