P/调用.如何通过C#编组调用非托管方法?

P/调用.如何通过C#编组调用非托管方法?

问题描述:

我对P/Invoke有问题.我正在从c#代码中调用.dll(在c ++上实现).有一个包含以下方法的类:

I've got a problem with P/Invoke. I'm calling .dll (implemented on c++) from c# code. There is a class, that contains the next methods:

virtual AudioFileList *API  CreateAudioFileList ()=0;
virtual bool API  DisposeAudioFileList (AudioFileList *iAudioFileList)=0;

AudioFileList 类如下:

AudioFileList class looks like:

virtual bool API  GetFile (long index, std::string *oPath, AudioFileInfo *fileInfo)=0;
virtual long API  GetNumberFiles ()=0; 

所以,问题是我该如何调用 CreateAudioFileList 方法,然后将结果传递给 DisposeAudioFileList 来自C#代码? 谢谢!

So, the question is how can I call CreateAudioFileList method and than pass the result to DisposeAudioFileList from C# code? Thanks!

由于名称修改,您不能这样做.您应该投资学习C ++/CLI.这样,您就可以创建一个中间层,该中间层提供适当的封送处理,并且不受C ++中名称处理的限制.

You can't, due to name mangling. You should invest in learning C++/CLI. This will allow you to create an intermediary layer that provides proper marshaling and isn't inhibited by name mangling in C++.

这是C ++/CLI中的样子(当然,未经测试):

Here's what it might look like in C++/CLI (untested, of course):

public ref class ManagedAudioFileList
{
private:
    const AudioFileList* Native;
    // Replace AudioFileListManager with the class containing
    // the CreateAudioFileList and DisposeAudioFileList methods.
    const AudioFileListManager* Manager;

public:
    ManagedAudioFileList(void);
    !ManagedAudioFileList(void);
    ~ManagedAudioFileList(void);
    // Insert various methods exposed by AudioFileList here.
};

.cpp

ManagedAudioFileList::ManagedAudioFileList(void)
{
    // Replace AudioFileListManager with the class containing the
    // CreateAudioFileList and DisposeAudioFileList methods.
    Manager = new AudioFileListManager();
    Native = Manager->CreateAudioFileList();
}

~ManagedAudioFileList::ManagedAudioFileList()
{
    Manager->DisposeAudioFileList(Native);
    delete Manager;
}

!ManagedAudioFileList::ManagedAudioFileList()
{
}

// Wrap various methods exposed by AudioFileList.