P/Invoke. How to call unmanaged method with marshalling from C#?

你。 提交于 2019-12-12 02:09:49

问题


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 class looks like:

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

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


回答1:


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++.

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

.h

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.



回答2:


I use this all the time to generate my static extern malarkey

http://clrinterop.codeplex.com/releases/view/14120




回答3:


Unfortunately, there is no easy way to call the classes in a native C++ DLL module through P/Invoke. Yet there's Visual C++ Team Blog post with a solution, but it is complicated.

There's one more link you might find useful: http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/5df04db1-bbc8-4389-b752-802bc84148fe/




回答4:


This article on CodeProject explains how to deal with this sort of marshalling.

How to Marshal a C++ Class



来源:https://stackoverflow.com/questions/9211128/p-invoke-how-to-call-unmanaged-method-with-marshalling-from-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!