c# 调用c库dll ,char*转string的解决办法
最近由于有個(gè)未知的設(shè)備需要用到modbus通訊協(xié)議,底層需要與PLC通訊,坤跌,PLC啥型號(hào)也不清楚封在里面不能拆,前人只留了幾個(gè)不能運(yùn)行的QT代碼以及不完整的文檔。用慣了C#想要重新學(xué)QT,真不知猴年馬月能完成項(xiàng)目。于是乎找了一個(gè)開源的基于C語言開發(fā)的modbus庫,擼起袖子干了起來。擼代碼的過程中,遇到調(diào)用c 庫的char*轉(zhuǎn)c#的string多次不成功的情況,各種冒框啊,折騰了大半天才算解決,最終記錄如下,以備后面遇到同樣的坑能少走點(diǎn)彎路。
.h file
#pragma once
#define LineMaxLen 2048 ?
#define KeyMaxLen 128 ?
#define MaxFileLength 1024*10 ?
#if defined(_MSC_VER)
# if defined(DLLBUILD)
/* define DLLBUILD when building the DLL */
# ?define MODBUS_API __declspec(dllexport)
# else
# ?define MODBUS_API __declspec(dllimport)
# endif
#else
# define MODBUS_API
#endif
?
static char value[KeyMaxLen];//需要定義為全局變量,編譯成dll后才能被c#正常調(diào)用,否則指針地址有數(shù)據(jù),指針內(nèi)容看到的返回值為空
?
MODBUS_API char* getValue();
MODBUS_API int sum(int a, int b);
?
#endif ?
.c file
char* getValue()//char key[KeyMaxLen]
{?? ??? ??? ?
?? ?memset(value, 0, sizeof(value));
?? ?strcpy(value, "abcdefgh");
?? ?return ?value;
}
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
?
namespace RotPlatformControl_CsDll
{
? ? public class CRotPlatformControl
? ? {
? ? ? ? [DllImport("modbus.dll", EntryPoint = "getValue", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
? ? ? ? public static extern IntPtr getValue();//不能用string,使用IntPtr對(duì)應(yīng)于c中的函數(shù)返回類型char*
? ? ? ??
? ? }
}
private void buttonHome_Click(object sender, EventArgs e)
????????{ ??????????
????????????IntPtr temp = CRotPlatformControl.getValue();
????????????res=Marshal.PtrToStringAnsi(temp).ToString();
????????????temp = IntPtr.Zero;
?
????????????lblMessage.Text = res.ToString();
????????}
UI顯示“abcdefgh” 說明dll已經(jīng)調(diào)用成功。
總結(jié):
1. const char* 直接換成string
2. char*做形參或返回值,需要換成IntPtr
3. char*做形參并想要獲取char*內(nèi)容,使用ref IntPtr無用。只能將該char*改為返回值獲得。
4. C庫文件中需要定義為全局變量,編譯成dll后才能被c#正常調(diào)用,否則指針地址有數(shù)據(jù),指針內(nèi)容看到的返回值為空。
modbus封庫源碼
https://download.csdn.net/download/ericwuhk/10352801
?
總結(jié)
以上是生活随笔為你收集整理的c# 调用c库dll ,char*转string的解决办法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: H.264编码技术
- 下一篇: Marshal在C#中的应用(void