使用C#程序模版
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
/* 我的第一個 C# 程序*/
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
添加命名空間
using System.Runtime.InteropServices;
添加調用聲明
在命名空間ConsoleApplication1
中添加一個類,用於聲明待調用的外部的C
庫函數
class MathCall
{
[DllImport(@"libmath.dll")]
public static extern int sub(int a, int b);
}
添加調用
在Main
函數中通過引用類成員的方法來調用函數
int n = MathCall.sub(9,1);
編譯
使用Visual Studio
的命令提示工具環境,編譯語句如下:
//編譯64位
csc.exe helloworld.cs
//編譯32位
csc.exe /platform:x86 helloworld.cs
要注意的地方
並不是用C#為開發語言,寫C#的目的也是為例演示如何調用自己的C庫,因此這里不說明C#語法,只是記錄與C/C++差異與調用C庫用到的一些細節。
- 在類里寫函數需要像
Main
函數一樣加static
聲明。 - 把庫函數聲明寫到一個類里,並加上
[DllImport(@"libmath.dll")]
和public static extern
聲明,后續函數通過類調用。 - 把C庫放到可執行程序路徑下。
- 可以使用
byte[]
代替unsigned char *
,類似的指針類的參數都轉換為數組。 - 可以使用
Array.Copy(src, des, len);
代替memory(des, src, len)
。 - 二維數組與一維數組。
//當作有10個64字節一維數組的二維數組
byte[] src = new byte[10*64];
byte[] des = new byte[64];
//源、源起始、目標、目標起始、拷貝長度
Array.Copy(src, 2*64, des, 0, 64);
- 分配空間不需要手動釋放
- while(1)要寫成while(true)