fly2323 2019-05-11 22:41 采纳率: 0%
浏览 516
已结题

c语言调用动态库中的函数,不能获取返回值,但C#可以,不知c代码该如何改进?vs2017环境下。

c语言:

typedef char * (__stdcall *MYPROC)(char * s, char * rs);//函数原型,s:传入数据,rs:返回数据。

HINSTANCE hinstLib;
MYPROC send;
BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;
WCHAR  msg[] = L"{\"head\":{\"jylsh\":\"330199103576000000000000001811\",\"xxlxm\":\"C009\",\"fhsj\":\"\",\"xxfhm\":\"\",\"fhxx\":\"\",\"yytcq\":\"330799\",\"zdjbh\":\"Test11111\",\"yljgdm\":\"8095\",\"czydm\":\"\",\"bbh\":\"1.0\"},\"data\":{\"ksjgs\":{\"klb\":\"12\",\"knsj\":\"A30533169330799D1560000050009A4378127B360\"}}}";
wprintf(L"%s", msg);
WCHAR P[] = L"";
char oututfmsg[1024] = { 0 };
WCHAR outmsg[2048] = { 0 };
char utfmsg[10240] = { 0 };
unicode_to_utf8((short *)msg, utfmsg);
hinstLib = LoadLibrary(TEXT("SendRcvB.dll"));
if (hinstLib != NULL)
{
    printf("begin GetProcAddres\n");
    send = (MYPROC)GetProcAddress(hinstLib, "SendRcv");
    if (NULL != send)
    {
        char * rcode = send(utfmsg, oututfmsg);//调试发现oututfmsg调用前后未发生变化
        fRunTimeLinkSuccess = TRUE;
}
    wprintf(L"%s", oututfmsg);
    fFreeResult = FreeLibrary(hinstLib);
}

c#代码如下:

    [DllImport("SendRcvB.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.StdCall)]
    private extern static IntPtr SendRcv(IntPtr sSend, out IntPtr sRcv);

    public Main()
    {
        InitializeComponent();
    }

    private void btn_fs_Click(object sender, EventArgs e)
    {
        try
        {
            string sRcv, sRs;
            string sIn = rTextIn.Text;
            byte[] tmpIn = gbkToUft8(sIn);
            IntPtr pIn = mallocIntptr(tmpIn.Length);
            Marshal.Copy(tmpIn, 0, pIn, tmpIn.Length);
            //IntPtr pIn = mallocIntptr(sIn);
            IntPtr pOut = IntPtr.Zero;
            IntPtr pRs  = IntPtr.Zero;
            pRs = SendRcv(pIn, out pOut);//pOut指针在变化,能指向返回数据
            sRcv = Marshal.PtrToStringUni(pOut);
            sRs   = Marshal.PtrToStringAnsi(pRs);
            sRcv = utf8ToGbk(sRcv);
            rTextOut.Text = sRcv;
            Marshal.FreeHGlobal(pIn);
        }
        catch (Exception oe)
        {
            MessageBox.Show(oe.Message);
        }
  • 写回答

1条回答

  • dabocaiqq 2019-05-12 10:31
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求码,CNN+LSTM实现单通道脑电信号EEG的睡眠分期评估
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路