使用C语言写DLL,在C#中调用

因为需要一段C语言实现的代码,无奈不了解其个中原理,想翻译为C#或python却有心无力,没有办法只有将C语言代码写成api函数,生成DLL,在C#中调用就算了吧

首先要有一个dll文件,其代码如下:

 encore.c

ContractedBlock.gif ExpandedBlockStart.gif Code
 1 #define  _UAPI  __declspec(dllexport)
 2 //定义宏
 3 
 4 _UAPI char *FToC(float f, int *a0, int *a1, int *a2, int *a3)
 5 {
 6     unsigned char a[4];
 7     memcpy(a, &f, 4);
 8     *a0 = (int)a[0];
 9     *a1 = (int)a[1];
10     *a2 = (int)a[2];
11     *a3 = (int)a[3];
12     return a;
13 }
14 
15 //将转换而来的整数存储与四个变量中

 

使用cl.exe工具编译它:cl /LD enCore.c,生成enCore.dll文件备用

在C#中调用它

 

ContractedBlock.gif ExpandedBlockStart.gif Code
 1 using System;
 2 using System.Runtime.InteropServices;
 3 public class MainClass 
 4 {
 5    [DllImport("enCore.dll",
 6         EntryPoint="FToC",
 7            CharSet=CharSet.Auto,
 8            CallingConvention=CallingConvention.StdCall
 9            )]
10    public static extern string FToC( float x, ref int a0, ref int a1, ref int a2, ref int a3);
11 
12    static void Main(string[] args) 
13    {
14        int a0 = 0, a1 = 0, a2 = 0, a3= 0;
15           string x = FToC((float)127.123ref a0, ref a1, ref a2, ref a3);
16         Console.WriteLine("{0}{1}{2}{3}",
17                    Convert.ToString(a0, 16), 
18                 Convert.ToString(a1, 16), 
19                 Convert.ToString(a2, 16),
20                    Convert.ToString(a3, 16));
21    }
22 }
23 

 

 

转载于:https://www.cnblogs.com/firefly_liu/archive/2009/05/13/1455967.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值