C#.NetからC関数を呼び出すことは可能ですか?質問する

C#.NetからC関数を呼び出すことは可能ですか?質問する

私は C ライブラリを持っており、このライブラリの関数を C# アプリケーションから呼び出したいと考えています。C ライブラリ ファイルをリンカー入力として追加し、ソース ファイルを追加の依存関係として追加することで、C ライブラリ上に C++/CLI ラッパーを作成しようとしました。

C# アプリケーションに C 出力を追加する方法がわからないため、これを実現するより良い方法はありますか。

私のCコード -

__declspec(dllexport) unsigned long ConnectSession(unsigned long handle,
                            unsigned char * publicKey,
                            unsigned char   publicKeyLen);

私のCPPラッパー -

long MyClass::ConnectSessionWrapper(unsigned long handle,
                                unsigned char * publicKey,
                                unsigned char   publicKeyLen)
    {
        return ConnectSession(handle, publicKey, publicKeyLen);
    }

ベストアンサー1

例えば、リナックス:

1)次の内容のCファイルを作成します。libtest.c

#include <stdio.h>

void print(const char *message)
{
  printf("%s\\n", message);
}

これは printf の単純な疑似ラッパーです。ただし、C呼び出したいライブラリ内の任意の関数を表します。関数がある場合は、名前が壊れないようにC++extern を忘れずに付けてください。C

2)C#ファイルを作成する

using System;

using System.Runtime.InteropServices;

public class Tester
{
        [DllImport("libtest.so", EntryPoint="print")]

        static extern void print(string message);

        public static void Main(string[] args)
        {

                print("Hello World C# => C++");
        }
}

3) ライブラリ libtest.so が「/usr/lib」などの標準ライブラリ パスにない場合は、System.DllNotFoundException が発生する可能性があります。これを修正するには、libtest.so を /usr/lib に移動するか、さらに良い方法として、CWD をライブラリ パスに追加します。export LD_LIBRARY_PATH=pwd

クレジットここ

編集

のためにウィンドウズあまり違いはありません。ここ*.cppファイルにメソッドをextern "C"次のように記述するだけです。

extern "C"
{
//Note: must use __declspec(dllexport) to make (export) methods as 'public'
      __declspec(dllexport) void DoSomethingInC(unsigned short int ExampleParam, unsigned char AnotherExampleParam)
      {
            printf("You called method DoSomethingInC(), You passed in %d and %c\n\r", ExampleParam, AnotherExampleParam);
      }
}//End 'extern "C"' to prevent name mangling

次にコンパイルし、C#ファイルで以下を実行します。

[DllImport("C_DLL_with_Csharp.dll", EntryPoint="DoSomethingInC")]

public static extern void DoSomethingInC(ushort ExampleParam, char AnotherExampleParam);

そしてそれを使用するだけです:

using System;

    using System.Runtime.InteropServices;

    public class Tester
    {
            [DllImport("C_DLL_with_Csharp.dll", EntryPoint="DoSomethingInC")]

    public static extern void DoSomethingInC(ushort ExampleParam, char AnotherExampleParam);

            public static void Main(string[] args)
            {
                    ushort var1 = 2;
                    char var2 = '';  
                    DoSomethingInC(var1, var2);
            }
    }

おすすめ記事