简体   繁体   中英

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

I've created a C# application. Within this application I would like to use/run a C++ API from another project(the API is written in macro coding). I tried import the dll of that C++ project and tried to call a functions which belongs to that API. The problem is that it throws "unable to find method" error.

How can I run a C++ project in a C# project?

You can't add a native DLL as a reference to a managed project. You have 3 main options:

  1. Make the native functions available with p/invoke.
  2. Expose the native code through COM.
  3. Compile the native code as a managed C++ assembly.

For any serious amount of code, option 3 is the most productive and effective approach.

If by "running", you mean a separate process:

Use the class System.Diagnostics.Process available in .NET:

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

Else, if you mean using a dll developed in C++, you can use 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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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