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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?