[.NET]c#调用DLL类中成员函数的一个例子

来源:互联网 发布:360软件应用下载 编辑:程序博客网 时间:2024/05/22 17:09

参照http://blogs.msdn.com/borisj/archive/2006/08/21/711530.aspx试验了一下如何在C#中调用DLL类成员函数,原文的例子没有试验成功,如果有人成功了,可以告知,谢谢!

vc.net2005下创建一个testDLL的project名字为testDLL,选择windows application,选择生成dll。

#pragma once

 

class __declspec(dllexport) HelloWorld

{

      
int foo;

public:

    HelloWorld()
{};

    
~HelloWorld(){};

      
void SayThis(wchar_t *phrase);

}
;

将此build成dll,名字为testDLL.dll。

新建一个C#的project,然后

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication2
{
    

    
class Program
    
{
        [DllImport(
"testDLL.dll", EntryPoint = "??1HelloWorld@@QAE@XZ")]

        
public static extern IntPtr HelloWorldNew();

        [DllImport(
"testDLL.dll", EntryPoint = "??4HelloWorld@@QAEAAV0@ABV0@@Z")]

        
public static extern void HelloWorldDelete(IntPtr hw);

        [DllImport(
"testDLL.dll",

                   EntryPoint 
= "?SayThis@HelloWorld@@QAEXPA_W@Z",

                    CharSet 
= CharSet.Unicode,

                    CallingConvention 
= CallingConvention.ThisCall)]

        
public static extern void SayThis(IntPtr thisptr, String phrase);
        
        
static void Main(string[] args)
        
{
            IntPtr hw 
= HelloWorldNew();

            SayThis(hw, 
"I'm a C# application using DllImport!");

  
//          HelloWorldDelete(hw);

        }

    }

}

其中,HelloWorldNew和HelloWorldDelete将HelloWorld类的构造函数和析构函数从DLL中暴露出来,使得C#能够PInvoke这些函数。这两个函数的CallingConvention缺省是stdcall,SayThis函数是thiscall,要明确指出。

另外这三个函数在PInvoke时候要指出entrypoint,可以通过vc.net的dumpbin工具查看dll文件看出dll文件原类成员函数变成什么样了,看起来像乱码.

最后一句HelloWorldDelete会报错,说程序访问受保护内存,刚开始学习.NET和平台调用,不懂,烦请指教。

原创粉丝点击