为什么我不能在C#项目中看到一些C ++ DLL(支持CLR)? [英] Why can't i see some C++ DLL ( support CLR ) in C# project ?
问题描述
我写了简单的C ++ Dll(win32),我将属性改为公共语言运行时支持(/ clr)' -
I wrote simple C++ Dll ( win32 ) and i change the properties to be 'Common Language Runtime Support (/clr)' -
我创建了一个简单的winform项目(C#4.0),我创建了对C ++项目(C ++ DLL)的引用。
I created new Simple winform project ( C# 4.0 ) and i created reference to the C++ project ( the C++ DLL ).
现在我看不到C ++项目中的C ++ dll它和我不知道为什么。
Now i can't see the C++ dll in the C# project - i cant use it and i dont know why.
推荐答案
如果您有此非管理功能:
If you have, for example, this unmanaged function:
bool fooFunction(int firstParameter, int secondParameter);
如果你想让它对托管代码可见,你必须换行)into一个托管类:
If you want to make it visible to managed code you have to wrap (as first, simple, step) it into a managed class:
public ref class MyClass abstract sealed
{
public:
static bool Foo(int firstParameter, int secondParameter)
{
return fooFunction(firstParameter, secondParameter);
}
};
这是一个简单的考试,如果你需要互动复杂类型,你可能需要将它们全部。例如,如果你必须与接受字符串的函数互操作,你必须管理它。通常我使用这样的类:
This is a simple exam, if you have to interop with complex type you may need to wrap them all. For example if you have to interop with a function that accepts a string you have to manage this. Usually I use a class like this:
ref class UnmanagedString sealed
{
public:
UnmanagedString(String^ content) : _content(content)
{
_unicodePtr = _ansiPtr = IntPtr::Zero;
}
~UnmanagedString()
{
Free();
}
operator LPWSTR()
{
if (_content == nullptr)
return NULL;
Free();
_unicodePtr = Marshal::StringToHGlobalUni(_content);
return reinterpret_cast<LPWSTR>(_unicodePtr.ToPointer());
}
operator LPCSTR()
{
if (_content == nullptr)
return NULL;
Free();
_ansiPtr = Marshal::StringToHGlobalAnsi(_content);
return reinterpret_cast<LPCSTR>(_ansiPtr.ToPointer());
}
virtual System::String^ ToString() override
{
return _content;
}
virtual int GetHashCode() override
{
return _content->GetHashCode();
}
virtual bool Equals(Object^ obj) override
{
return _content->Equals(obj);
}
private:
IntPtr _unicodePtr, _ansiPtr;
String^ _content;
void Free()
{
if (_unicodePtr != IntPtr::Zero)
{
Marshal::FreeHGlobal(_unicodePtr);
_unicodePtr = IntPtr::Zero;
}
if (_ansiPtr != ntPtr::Zero)
{
Marshal::FreeHGlobal(_ansiPtr);
_ansiPtr = IntPtr::Zero;
}
}
};
< 与 foo(UnamangedString(myManagedString))
。
注意:只需将一个1:1的托管接口暴露给非托管函数,就会产生更复杂的问题。使你的C#代码更难读,我建议你写一个真正的OO界面来隐藏底层实现。
Note: simply exposing a 1:1 managed interface to unmanaged functions will make your C# code harder to read, I suggest you write a true OO interface to hide underlying implementation.
这篇关于为什么我不能在C#项目中看到一些C ++ DLL(支持CLR)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!