您的位置:逆风者 VC++ 正文
 添加时间:2007-09-01 原文发表:2007-08-31 人气:111 来源:vckbase.com

本文章共3290字,分3页,当前第2页,快速翻页:
 

LIBEXPORT_API char *mySum(char *a,char *b){sprintf(b,"%s",a) return b;}

修改 C# 导入定义,将串b修改为ref方式:

public class RefComm

{

[DllImport("LibEncrypt.dll", 

     EntryPoint=" mySum ",

     CharSet=CharSet.Auto,CallingConvention=CallingConvention.StdCall)] 

     public static extern string mySum (string a, ref string b);

}

逆风编程精品
在C#中再调用测试:

string strDest="";

string strTmp= RefComm.mySum("12345", ref strDest);

  运行查看结果 strTmp 和 strDest 均不对,含不可见字符。再修改 C# 导入定义,将CharSet从Auto修改为Ansi:

public class RefComm

{

[DllImport("LibEncrypt.dll", 

     EntryPoint=" mySum ",

     CharSet=CharSet.Ansi,CallingConvention=CallingConvention.StdCall)] 

     public static extern string mySum (string a, string b);

}

在C#中再调用测试:

string strDest="";

string strTmp= RefComm. mySum("12345", ref strDest);

  运行查看结果 strTmp 为"12345",但是串 strDest 没有赋值。第二步实现函数返回串,但是在函数出口参数中没能进行输出。再次修改 C# 导入定义,将串b修改为引用(ref):

public class RefComm

{

[DllImport("LibEncrypt.dll", 

     EntryPoint=" mySum ",

     CharSet=CharSet.Ansi,CallingConvention=CallingConvention.StdCall)] 

     public static extern string mySum (string a, ref string b);

}

运行时调用失败,不能继续执行。

第三步,修改动态链接库实现,将b修改为双重指针:

LIBEXPORT_API char *mySum(char *a,char **b){sprintf((*b),"%s",a); return *b;}

C#导入定义:

public class RefComm

{

[DllImport("LibEncrypt.dll", 

     EntryPoint=" mySum ",

     CharSet=CharSet.Ansi,CallingConvention=CallingConvention.StdCall)] 

     public static extern string mySum (string a, ref string b);

}

在C#中调用测试:

string strDest="";

string strTmp= RefComm. mySum("12345", ref strDest);

  运行查看结果 strTmp 和 strDest 均为"12345",调用正确。第三步实现了函数出口参数正确输出结果。

第四步,修改动态链接库实现,实现整数参数的输出:

LIBEXPORT_API int mySum(int a,int b,int *c){ *c=a b; return *c;}

C#导入的定义:

public class RefComm

{

[DllImport("LibEncrypt.dll", 

     EntryPoint=" mySum ",

     CharSet=CharSet.Ansi,CallingConvention=CallingConvention.StdCall)] 

     public static extern int mySum (int a, int b,ref int c);

}

在C#中调用测试:

int c=0;

int iSum= RefComm. mySum(2,3, ref c);

运行查看结果iSum 和c均为5,调用正确。
  经过以上几个步骤的试验,基本掌握了如何定义动态库函数以及如何在 C# 定义导入,有此基础,很快我实现了变长加密函数在 C# 中的调用,至此目标实现。

三、结论
  在 C# 中调用 C 编写的动态链接库函数,如果需要出口参数输出,则需要使用指针,对于字符串,则需要使用双重指针,对于 C# 的导入定义,则需要使用引用(ref)定义。
 

本文章更多内容<<上一页 - 1 - 2 - 3 - 下一页>>
相关文章

DLL头文件的格式和应用
用 Web 服务进行二进制序列化和 BinaryForm
QQ2006 界面编程之鸡蛋里挑骨头
在你的程序中如何使用CButtonST类
Buffer Overruns,portability和其它...
自动隐藏停泊窗体实现
模拟 Windows 下 CPU 占用率的控件及其实现
VC中基于 Windows 的精确定时
DLL初学者指南(非MFC)
如何使用BHO定制你的Internet Explorer浏览
软件测试悖论
VC 操作 SQL Server 主从表
C语言高效编程的几招
软件框架的利器、TangramMini组件应用教程二
GDI和GDI 对象的相互转换
PE文件格式详解(下)
计算MDI子窗口数,仅显示文件夹的打开对话框
基于MFC对话框的NT服务程序框架
关于控件注册和使用许可问题的解决办法
汉诺塔游戏的设计

相关评论


本文章所属分类:首页 VC++

  热门关键字: