C/C++/C# 调用C/C++ Dll

1  Dll文件

   
 //MyDll.h
   extern"C" _declspec(dllexport) int addTest(int a,int b);

   // MyDll.cpp: 定义 DLL 应用程序的导出函数。
   //

 

   #include "stdafx.h"
   #include "MyDll.h"
   #include <iostream>

   int addTest(int a,int b)
   {
       return a+b;
   }



2 C++调用Dll

   //CallMyDll.h

 

 #ifndef _CALL_MY_DLL_
   #define _CALL_MY_DLL_

   #include "windows.h"

   typedef int(*pAdd)(int a,int b);
    HINSTANCE HDll;

   #endif


   // CallMyDll.cpp: 定义控制台应用程序的入口点。

 

   #include "CallMyDll.h"
   #include "stdafx.h"

   int _tmain(int argc, _TCHAR* argv[])
   {
      HDll = LoadLibrary(L"MyDll.dll");
      pAdd pAddCall = (pAdd)GetProcAddress(HDll,"addTest");

      int m = pAddCall(3,6);
      //cout<<"m = "<<m<<endl;
      printf("m = %d",m);
      return 0;
   }


3 C#调用dll

调试代码 ,解决方案 添加项目

/*设置:项目/右击 属性/调试/启用调试器/启用非托管代码调试*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace CsCallCDll
{
    class Program
    {
        [DllImport(@"MyDll.dll", EntryPoint = "addTest", CallingConvention = CallingConvention.Cdecl)]
        public static extern int addTest(int a, int b);


        static void Main(string[] args)
        {
            int iTest = addTest(2,5);
            Console.WriteLine("iTest = {0}",iTest);
        }

    }
}


问题:弹出如下提示
托管调试助手“PInvokeStackImbalance”在“D:\My Documents\Visual Studio 2008\Projects\CsCallMyDll\bin\Debug\CsCallMyCDll.exe”中检测到故障。
其他信息: 对 PInvoke 函数“CsCallMyCDll!CsCallCDll.Program::addTest”的调用导致堆栈不对称。原因可能是托管的 PInvoke 签名与非托管的目标签名不匹配。请检查 PInvoke 签名的调用约定和参数与非托管的目标签名是否匹配。

[DllImport(@"MyDll.dll")]

改为:
[DllImport(@"MyDll.dll", EntryPoint = "addTest", CallingConvention = CallingConvention.Cdecl)]



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值