最近用c#写一个小软件,要调用VC写的dll,传递参数给dll,由于是非托管代码,所以调用起来有点麻烦,要把参数转换成非托管代码的指针参数,然后再传递给dllview plaincopy to clipboardprint?
using System.Runtime.InteropServices; //操作Dll的类空间
class CGicomIndex
{
[DllImport("Index_dll.dll")]
unsafe private static extern Int32 create_index_file(IntPtr filename, IntPtr fieldname, UInt32 tongshu, IntPtr err);
//VC原型 create_index_file( char*filename, char * fieldname, unsigned long tongshu, char *err);
#region " bool CreateIndexFile( string m_strFileName, string m_strFieldName, UInt32 m_key, ref string strErr ) 对DBF文件按照指定的字段创建索引"
/// <summary>
/// 对DBF文件按照指定的字段创建索引
/// </summary>
/// <param name="m_strFileName">DBF文件路径</param>
/// <param name="m_strFieldName">创建索引的字段名称</param>
/// <param name="m_key">索引桶数(文件记录的最大数)</param>
/// <param name="strErr">出错信息</param>
/// <returns>成功 true</returns>
public static bool CreateIndexFile( string m_strFileName, string m_strFieldName, UInt32 m_key, ref string strErr )
{
try
{
IntPtr ptrFileName, ptrFieldName, ptrErr;
//根据数据的长度申请非托管空间
ptrFileName = mallocIntptr(m_strFileName);
ptrFieldName = mallocIntptr(m_strFieldName);
ptrErr = mallocIntptr(300);
//创建索引
if (create_index_file(ptrFileName, ptrFieldName, m_key, ptrErr) != 1)
{
strErr = Marshal.PtrToStringAnsi(ptrErr);
Marshal.FreeHGlobal(ptrFileName);
Marshal.FreeHGlobal(ptrFieldName);
Marshal.FreeHGlobal(ptrErr);
return false;
}
Marshal.FreeHGlobal(ptrFileName);
Marshal.FreeHGlobal(ptrFieldName);
Marshal.FreeHGlobal(ptrErr);
return true;
}
catch (System.Exception ex)
{
strErr = ex.Message;
return false;
}
}
#endregion
#region " IntPtr mallocIntptr( string strData ) 根据数据的长度申请非托管空间"
/// <summary>
/// 根据数据的长度申请非托管空间
/// </summary>
/// <param name="strData">要申请非托管空间的数据</param>
/// <returns>指向非拖管空间的指针</returns>
private static IntPtr mallocIntptr( string strData )
{
//先将字符串转化成字节方式
Byte[] btData = System.Text.Encoding.Default.GetBytes(strData);
//申请非拖管空间
IntPtr m_ptr = Marshal.AllocHGlobal(btData.Length);
//给非拖管空间清0
Byte[] btZero = new Byte[btData .Length+ 1]; //一定要加1,否则后面是乱码,原因未找到
Marshal.Copy(btZero, 0, m_ptr, btZero.Length);
//给指针指向的空间赋值
Marshal.Copy(btData, 0, m_ptr, btData.Length);
return m_ptr;
}
/// <summary>
/// 根据长度申请非托管空间
/// </summary>
/// <param name="strData">要申请非托管空间的大小</param>
/// <returns>指向非拖管空间的指针</returns>
private static IntPtr mallocIntptr( int length )
{
//申请非拖管空间
IntPtr m_ptr = Marshal.AllocHGlobal(length);
//给非拖管空间清0
Byte[] btZero = new Byte[length + 1]; //一定要加1,否则后面是乱码,原因未找到
Marshal.Copy(btZero, 0, m_ptr, btZero.Length);
//给指针指向的空间赋值
Marshal.Copy(btZero, 0, m_ptr, length);
return m_ptr;
}
#endregion
}
到此这篇关于C# 调用Dll 传递字符串指针参数的文章就介绍到这了,更多相关C# 字符串指针参数内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!