Q&A
C++のクラスをC#で利用したいため、CLIラッパクラスを作成しています。
c#からc++のメソッドを呼ぶ際、const char*型のメソッドを呼ぶ際に
CS0214 ポインターおよび固定サイズ バッファーは、unsafe コンテキストでのみ使用することができます
とエラーが表示されており呼び出すことができません。
いくつかサイトを検索してみましたが、参考になるページが見つからなかったためご教示お願いいたします。
Test.h
1#ifdef DLL_EXPORTS 2#define DLL_API __declspec(dllexport) 3#else 4#define DLL_API __declspec(dllimport) 5#endif 6 7#include <memory> 8#include <string> 9#include <vector> 10#include <cstddef> 11 12namespace qrk 13{ 14 class DLL_API Dll 15 { 16 public: 17 const char* name(void) const; 18 19private: 20 struct pImpl; 21 std::auto_ptr<pImpl> pimpl; 22 23 }; 24}
Test.cpp(cppファイル)
1#include "pch.h" 2#include "Test.h" 3 4using namespace qrk; 5using namespace std; 6 7struct Test::pImpl 8{ 9 product_t product_; 10 11 string name_; 12 13 14 pImpl(void) 15 :last_measure_type_(Distance), time_stamp_offset_(0) 16 { 17 urg_t_initialize(&urg_); 18 } 19}; 20 21Test::Test(void) : pimpl(new pImpl) 22{ 23} 24 25Test::~Test(void) 26{ 27} 28 29const char* qrk::Test::name(void) const 30{ 31 if (pimpl->name_.empty()) { 32 pimpl->name_ = product_name(&pimpl->product_); 33 } 34 return pimpl->name_.c_str(); 35} 36
WrapperClass.h(ラッパクラスのヘッダファイル)
1#include "../Test/Test.h" 2 3using namespace System; 4using namespace System::Runtime::InteropServices; 5using namespace System::Collections::Generic; 6 7namespace Wrapper 8{ 9 public ref class WrapperClass 10 { 11 12 private: 13 qrk::Test* _test; 14 15 public: 16 WrapperClass(); 17 ~WrapperClass(); 18 !WrapperClass(); 19 20 const char* name(void); 21 22 }; 23} 24
WrapperClass.cpp(ラッパクラス)
1#include "pch.h" 2 3#include "WrapperClass.h" 4 5using namespace System; 6using namespace System::Runtime::InteropServices; 7 8Wrapper::WrapperClass::WrapperClass() 9{ 10 _test = new qrk::Test(); 11} 12 13Wrapper::WrapperClass::~WrapperClass() 14{ 15 delete _test; _test = nullptr; 16} 17 18Wrapper::WrapperClass::!WrapperClass() 19{ 20 this->~WrapperClass(); 21} 22 23const char* Wrapper::WrapperClass::name(void) 24{ 25 return _test->name(); 26} 27
Sample.cs(C#のクラス)
1using System; 2using System.Collections.Generic; 3using System.Linq; 4using System.Text; 5using System.Threading.Tasks; 6using System.Runtime.InteropServices; 7using Wrapper; 8 9namespace SampleTest 10{ 11 public class Sample 12 { 13 //WrapperClassのインスタンスを作成 14 WrapperClass wr = new WrapperClass(); 15 16 public bool getSensorParameter() 17 { 18 if (wr.name() == "") //CS0214 ポインターおよび固定サイズ バッファーは、unsafe コンテキストでのみ使用することができます 19 { 20 return false; 21 } 22 return true; 23 } 24 25 } 26}
回答2件
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
2022/03/09 01:22
2022/03/09 02:12
2022/03/09 02:18
2022/03/09 02:28