加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

VS2010里C#调用C++ dll文件(数字及字符串传参)

(2012-07-18 18:23:26)
标签:

vs2010

c

dll

接口

杂谈

分类: 学习
查了一些资料,貌似说.net 3.5 和.net4.0调用c++ dll的方式不用,我没试验过,一直用的VS2010,如果以下方法有人不适用,可能有这方便原因。

C++部分 
stdafx.h:
#include "targetver.h"

#define WIN32_LEAN_AND_MEAN             // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>

// TODO: reference additional headers your program requires here
#ifndef LIB_H
#define LIB_H
extern "C" int _declspec(dllexport)add(int x,int y);    // 声明为C编译、链接方式的外部函数
extern "C" _declspec(dllexport)  char* Suma(char* a, char* b);
#endif

TestDLL.cpp
#include "stdafx.h"

int add(int x,int y)
{
    return x+y;
}

char* Suma(char* a, char* b)
{
char* result = (char*)LocalAlloc(LPTR, strlen(a) + strlen(b) + 1);
strcat(result, a);
strcat(result, b);
return result;
}

C#部分:
program.cs

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("result: " + test.add(-12, 3).ToString());
            string a = "Hola";
            string b = "Jose";
            IntPtr p = test.Suma(a, b);
            string c = Marshal.PtrToStringAnsi(p);
            Marshal.FreeHGlobal(p);
            Console.WriteLine(c);
            Console.ReadLine();
        }
    }

    class test
    {
        [DllImport("TestDLL.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int add(int i, int j);

        [DllImport("TestDll.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern System.IntPtr Suma(string a, string b);
    }

之前在调试的时候虽然结果运行正确,但一直出现错误提示,
“Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in...."
在DLLImport中加入CallingConvention = CallingConvention.Cdecl就ok了
KEY WORDS:  either use __stdcall on your C++ function or declareCallingConvention = CallingConvention.Cdecl on your DllImport.

ok,问题解决了

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有