在.net C#里怎样调用非托管动态库函数dll?

 这里讲述的是C#调用标准动态库的问题, 在我以前的文件中讲到过, C#调用Win32API, 原理是一样的. 这里我详细讲解用C写一个标准的动态库, 然后让C#调用. (本篇适合初学者, 中间没有任何冗余代码, 简洁明了)
 软件环境: VC6.0(当然其他版本的VC5也可以)
 1.制作标准动态库
__declspec(dllexport) int __cdecl add(int, int);//这一句是声明动态库输出一个可供外不调用的函数原型.
int add(int a,int b) {//实现这个函数
 return a+b;
}
以上简单3行代码,声明一个add的方法, 输入参数是两个int参数,返回这两个数之和. 保存为MyLib.c
然后执行编译命令.
H:/XSchool/C#-School/HowTo>cl /LD MyLib.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8168 for 80x86
Copyright (C) Microsoft Corp 1984-1998. All rights reserved.

MyLib.c
Microsoft (R) Incremental Linker Version 6.00.8447
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.

/out:MyLib.dll
/dll
/implib:MyLib.lib
MyLib.obj
   Creating library MyLib.lib and object MyLib.exp

确信有以上输出, 说明编译成功生成了动态库.

 2.编写C-Sharp程序调用该动态库
using System;
using System.Runtime.InteropServices;//这是用到DllImport时候要引入的包

public class InvokeDll {
 [DllImport("MyLib.dll", CharSet=CharSet.Auto)]
 static extern int add(int a,int b);//声明外部的标准动态库, 跟Win32API是一样的.
 
 public static void Main() {
  Console.WriteLine(add(10,30));
 }
}
保存为InvokeDll.cs文件, 与MyLib.dll置于同一目录, 编译该文件.
H:/XSchool/C#-School/HowTo>csc invokedll.cs
将生成Invokedll.exe, 可以执行该文件.

--------------------------------------------------------------------------------------------------------------------------------------

         
         
C#.net 调用Dll 参数传递问题 [DllImport("k8110.dll")] static extern bool CAN_Init(long iIndex, ref Byte[] config);//把他转到C# //Public Declare Function CAN_Init Lib "k8110.dll" (ByVal iIndex As Long, ByRef config As Any) As Boolean /这个是vb 的代码 Byte[] Conf = new Byte[5]; Conf[0] = 1; Conf[1] = 2; Conf[2] = 3; Conf[3] = 4; Conf[4] = 5; OpenReturn = CAN_Init(0, ref Conf);//get a Error //Attempted to read or write protected memory. This is often an indication that other memory is corrupt. 咋整!
 
 回复人:Mittermeyer(疾风之狼) 2006-04-29 09:22:00得分:0
 
 
?
         
         
static extern bool CAN_Init(long iIndex, Byte[] config) OpenReturn = CAN_Init(0, Conf) 这样应该就可以了。
Top
 
 回复人:Ninputer(装配脑袋) 2006-04-29 09:27:00得分:0
 
 
?
         
         
[DllImport("k8110.dll")] static extern int CAN_Init(int iIndex, [MarshalAs(UnmanagedType.LPArray)]Byte[] config); 好多类型都错了,数组和string绝对不能ref传递给API

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值