[C#互操作] C#调用非托管dll接口的返回值问题

路客尘 2015-12-03 11:29:51
各位好!

我编写了一个c的dll,有一个导出接口为test

long test()
{
return 0;
}


在C# 中使用时,发现该函数的返回值为 254837555181125632这么一个很长的预料之外的值。
但是使用C语言编写的程序来加载该dll函数时,得到的值是0,是预料之中的值。
===========================================
我猜想是否和编译器不同有关,或者与语言的处理方式有关?。

于是,我更改了dll接口的内部代码,添加了汇编部分

long test()
{
__asm {
//xor eax, eax;
//xor ebx, ebx;
//xor ecx, ecx;
xor edx, edx;
}
return 0;

}
}

只要执行了这个 xor edx, edx;,在C# 中取得的返回值就是想要的0.
===================================
以前,用BCB调用vc的接口时,也有类似的问题,如果要返回0,需要额外清空dx,在bcb中才能取得正确的返回值0.

我想知道,为什么C的dll接口中的return 0针对C# 没有效果?
...全文
133 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
bdmh 2015-12-03
  • 打赏
  • 举报
回复
把你c#代码贴出来,肯定是你的问题
路客尘 2015-12-03
  • 打赏
  • 举报
回复
引用 5 楼 u012948520 的回复:
你先看看你C++ 里面的long是32位还是64位
谢谢你的提醒哈!估计是这个问题! C++中是32位,C#中是64位的! 我最近这脑子
路客尘 2015-12-03
  • 打赏
  • 举报
回复
引用 4 楼 wyd1520 的回复:
long test() {} public static extern long PG_LoadItemCode(IntPtr handle, string path); 这两怎么也对应不上呀
O(∩_∩)O谢谢 test只是为了举例说明一下
路客尘 2015-12-03
  • 打赏
  • 举报
回复
引用 3 楼 shingoscar 的回复:
long和long是不一样的,明白不?
( ⊙ o ⊙ )啊! 我怎么给疏忽了。。。。。谢谢啊
白衣如花 2015-12-03
  • 打赏
  • 举报
回复
你先看看你C++ 里面的long是32位还是64位
本拉灯 2015-12-03
  • 打赏
  • 举报
回复
long test() {} public static extern long PG_LoadItemCode(IntPtr handle, string path); 这两怎么也对应不上呀
Poopaye 2015-12-03
  • 打赏
  • 举报
回复
long和long是不一样的,明白不?
路客尘 2015-12-03
  • 打赏
  • 举报
回复
声明导入的接口

/// <summary>
        /// 加载prg文件.
        /// </summary>
        /// <param name="handle">指向PG_HANDLE结构的指针,从PG_LoadSpecCode获得</param>
        /// <param name="path">*.prg文件的路径</param>
        /// <returns>if ok, 0; else if -9: speccode未加载; else -1;</returns>
        /// <remarks>使用前,应该先调用PG_LoadSpecCode,获取对应的handle</remarks>
        [DllImport("Prog32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        public static extern long PG_LoadItemCode(IntPtr handle, string path);
使用:

private void btnLoad_Click(object sender, EventArgs e)
        {
            ptrSpec = Prog32DllAPI.PG_LoadSpecCode(strSpecPath);
            Msg(ptrSpec.ToString());
            long ret = Prog32DllAPI.PG_LoadItemCode(ptrSpec, strPrgPath);
            Msg(ret.ToString());
            switch (ret)
            {
                case 0:
                    Msg("Read " + strPrgPath + " OK!");
                    break;
                case -1:
                    Msg("Failed to load" + strPrgPath + "!");
                    break;
                case -9:
                    Msg("Speccode not loaded!");
                    break;
            }
        }

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧