日期:2014-05-18  浏览次数:20924 次

c# 调用DLL 参数问题
我现在遇到一个问题。 是调用一个dll。 发现其参数是有指针。不知道应该如何写。

int FL_GetFea(int nAddr, unsigned char* pTemplet, int* iTempletLength);



我改写成下面那样出现了错误

 public static extern int FL_GetFea(int nAddr, IntPtr pTemplet, IntPtr iTempletLength);
   
  int fl_GetFea(int nAddr, string pTemplet, int iTempletLength)
  {
  return FL_GetFea(nAddr, pTemplet, iTempletLength);
  }

------解决方案--------------------
等待学习
------解决方案--------------------
试试参数用ref。
------解决方案--------------------
引自:http://blog.csdn.net/ghlfllz/archive/2010/10/10/5931291.aspx

有两种办法在C#中调用C++写的DLL的方法有两种:

1、COM

将C++代码封装成COM,然后在C#中引用

2、API

将C++代码封装成C接口的函数,类似于Windows的API,然后在C#中通过DllImport引用

例如:

c++头文件为

int _stdcall Decrypt(unsignec char *src, unsigned long src_len, unsigned char **dst, unsigned long *dst_len);

注:在*.def文件中需呀为定义Decrypt的导出

在c#中引用如下命名空章

using System.Runtime.InteropServices;

在某个类的构造函数后面添加:

[DllImport("CryptTools.dll")]

internal static extern int Decrypt(System.IntPtr src, int src_len, ref System.IntPtr dst, ref int dst_len);

添加函数封装对该API的调用:

internal static int Sharp_Decrypt(byte[] src, ref byte[] dst)

{

int result = -1, dstLen = 0;

IntPtr pSrc = Marshal.AllocHGlobal(src.Length);

Marshal.Copy(src, 0, pSrc, src.Length);

IntPtr pDst = IntPtr.Zero;

result = Decypt(pSrc, src.Length, ref pDst, ref dstLen);

if (0 == result)

{

dst = new byte[dstLen];

Marshal.Copy(pDst, dst, 0, dstLen);

}

Marshal.FreeHGlobal(pSrc);

return result;

}

请注意,出于篇幅的考虑,此处没有在CryptTools.dll中添加unsigned char**的释放函数,需要读者自行添加。
------解决方案--------------------
int FL_GetFea(int nAddr, unsigned char* pTemplet, int* iTempletLength);
第二个参数是一个字符串指针,应该是用来写数据的
第三个参数在传入的时候应该是指明第二个参数的长度,在传出的时候指明实际写了多少字节数据
试试这样:
int aAddr;
StringBuilder sb = new StringBuilder(256);
int length = 256;
GetFea(nAddr, sb, ref length);
------解决方案--------------------
等待学习中
------解决方案--------------------
我对最后一个参数的方法有误,写了点代码测试了一下:
C/C++ Dll代码:
C/C++ code
#include "stdafx.h"
#include <stdio.h>

extern "C" __declspec(dllexport) void GetName(char* buffer, int* size)
{
    printf("before copy the length is:%d\n", *size);//写数据前buffer的容量
    char temp[] = "hello,world";
    strcpy(buffer,temp); //模拟写数据
    printf("OK, string is:%s\n", buffer);
    *size = (int)strlen(temp);
    printf("after copy the length is:%d\n", *size);//写数据后buffer的容量
}

------解决方案--------------------
C# code

 [DllImport()]
 public static extern int FL_GetFea(int nAddr,ref byte[] pTemplet,ret int iTempletLength);
pTemplet, iTempletLength 可能是输入参数。 
你看看API,