我想防止垃圾收集器重新定位移动变量。我需要设置一个指向托管变量的指针(我要创建一个指针),并在执行过程中“锚定”该变量。
换句话说,如何将C#代码转换为Java?:
fixed (Char* sPtr = s) {
//s = any String variable
return convertToSomething(sPtr, s.Length); //Any method
}
String s = ...;
return convertToSomething(s, s.length());
如果s
是多线程环境中的实例变量,那么您可以简单地将引用“复制”到您的方法中:
private volatile String s; // should be volatile, else you may work with stale references
public Something yourMethod() {
String sLocal = s; // copy the reference, sLocal will be the value of s at the time the method was invoked
return convertToSomething(sLocal, sLocal.length());
}