0

我有一个包含静态 C++ 库的 CLR C++ dll。我有以下课程:

#pragma once

#include <windows.h>
#include <sddl.h>

#include <LibEx.h>
using namespace System;
#using <mscorlib.dll>

namespace LIB_WrapperNamespace {

    public ref class LIB_WrapperClass
    {
    public:
        BOOL WINAPI T_LibEx_ConsoleConnect(IN DWORD num1, IN LPWSTR Name)
        {
            return LibEx_ConsoleConnect(num1,Name);
        }
        };
} 

在 C# 中,我添加了对库的引用

LIB_WrapperNamespace.LIB_WrapperClass myLib = new LIB_WrapperNamespace.LIB_WrapperClass();

现在如何调用这个函数,如何将字符串发送到 char*?来自 C#:

string myName = "NAME";
myLib.T_LibEx_ConsoleConnect(1,**myName**);
4

2 回答 2

2

API 应该将该参数公开为 a,wchar_t*因此您需要在 C# 中提供一个指针值。尝试以下

IntPtr ptr = IntPtr.Zero;
try { 
  ptr = Marshal.StringToCoTaskMemUni("NAME");
  unsafe { 
    myLib.T_LibEx_Consoleconnect(1, (char*)(ptr.ToPointer()));
  }
} finally { 
  if (ptr != IntPtr.Zero) { 
    Marshal.FreeCoTaskMem(ptr);
  }
}

不幸的是,由于您已经使用原始指针值公开了该方法,因此没有unsafe代码就无法从 C# 中使用它。另一种方法是公开一个重载,例如 a string^。这可以从 C# 中使用,并且 C++/CLI 代码可以处理从string^到的编组LPWSTR

BOOL WINAPI T_LibEx_ConsoleConnect(DWORD num1, String^ Name) { 
   IntPtr ip = Marshal::StringToHGlobalUni(Name);
   BOOL ret = T_LibEx_ConsoleConnect(num1, static_cast<LPWSTR>(ip.ToPointer()));
   Marshal::FreeHGlobal(ip);
   return ret;
}

// From C#
myLib.T_LibEx_ConsoleConnect(1, "NAME");
于 2013-07-30T17:48:44.470 回答
0

当您将封送处理问题“暴露”给包装器的用户时,为什么要构建 C++\CLI 项目来包装某些东西?C++\CLI 的想法是将封送处理问题隐藏在包装器内。您应该为 .NET 本地声明该函数:

#pragma once

#include <Windows.h>
#include <stdlib.h>
#include <string.h>
#include <msclr\marshal_cppstd.h> 
#include <vector>

namespace ClassLibrary2 {
public ref class Class1
{
public:
    //Expose .NET types to .NET users.
    System::Boolean T_LibEx_ConsoleConnect(System::UInt64 num1, System::String^ Name);
};

}

并实现这个包装函数,你可以按照你的感觉进行编组,它可能看起来像这样:

#include "ClassLibrary2.h"

namespace ClassLibrary2 {
System::Boolean Class1::T_LibEx_ConsoleConnect(
    System::UInt64 num1, 
    System::String^ Name)
{
    //Initialize marshaling infrastructure. You can use its instance many times 
    //through out life span of your application.
    msclr::interop::marshal_context^ marshalContext = gcnew msclr::interop::marshal_context();

    //Turn System::String into LPWSTR. Keep in mind that you are now the owner of 
    //memory buffer allocated for unmanagedName. You need to release it somewhere.
    const wchar_t* clsConstChars = marshalContext->marshal_as<const wchar_t*>(Name);
    LPWSTR unmanagedName = const_cast<LPWSTR>(clsConstChars);

    //System::UInt64 num1 will be marshalled to DWORD natively by compiler.
    return LibEx_ConsoleConnect(num1, unmanagedName);
}}
于 2013-07-30T19:12:33.653 回答