Skip to content

An exception occurred in C# dll generated by C++ #1

@Balcher

Description

@Balcher

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);
         ...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions