An exception occurred in C# dll generated by C++
I am a beginner in C#. I wrote a method in C++ to process vtkPolyData, wrapped it into a DLL for use in C# environment. In C#, I'm using pointers to pass parameters, but encounter a error
'System.AccessViolationException: Attempted to read or write protected memory. This usually indicates that other memory is corrupt.'
Initially, I thought it might be a method issue, but the same method works fine with OpenCV."
the code in c++ is
DLL_EXPORT_DECL void CallingConvention mytest(void* srcPtr)
{
vtkPolyData* myin = static_cast<vtkPolyData*>(srcPtr);
std::cout << "myin address: " << myin << std::endl;
if (myin == nullptr) {
std::cout << " myin == nullptr " << std::endl;
std::cerr << "Error: myin is nullptr" << std::endl;
return;
}
std::cout << "skip if " << std::endl;
std::cout << "Number of points: " << myin->GetNumberOfPoints() << std::endl;
std::cout << "end mytest" << std::endl;
}
code in C# is :
class Class1
{
...
[DllImport("delaunayLib.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "mytest", CharSet = CharSet.Auto)]
public static extern void mytest(IntPtr myin);
...
}
use dll in C# the code is ï¼
...
vtkPolyData polydata = vtkPolyData.New();
polydata.SetPoints(points);
polydata.GetPointData().SetScalars(colors_rgb);
IntPtr srcPtr = (IntPtr)polydata.GetCppThis();
Class1.mytest(srcPtr);
...
The memory addresses printed in C# and c++ are the same: in C#
|  | åç§° | å¼ | ç±»å |
|---|---|---|---|
| Â | srcPtr | 0x000001f3b363bb10 | System.IntPtr |
in C++: myin address: 000001F3B363BB10
The detailed error message is
System.AccessViolationException
HResult=0x80004003
Message=å°è¯è¯»åæåå
¥åä¿æ¤çå
åãè¿é常æç¤ºå
¶ä»å
åå·²æåã
Source=<æ æ³è®¡ç®å¼å¸¸æº>
StackTrace:
<æ æ³è®¡ç®å¼å¸¸å æ è·è¸ª>
The same calling method works with opencvï¼
in C++
DLL_EXPORT_DECL void CallingConvention myopencvTest(cv::Mat* img)
{
std::cout << " img.size = " << (*img).size() << std::endl;
}
in C#
...
class Class1
{
[DllImport("delaunayLib.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "myopencvTest", CharSet = CharSet.Auto)]
public static extern void myopencvTest(IntPtr img);
}
...
string image_path = "C:\\Users\\bck\\Desktop\\photo.png";
Mat img = Cv2.ImRead(image_path);
Cv2.ImShow("img", img);
Class1.myopencvTest(img.CvPtr);
...
可以试试看在c#代码里直接使用指针,你需要启用不安全代码
unsafe
{
void* srcPtr = polydata.GetCppThis().ToPointer();
Class1.mytest(srcPtr);
}