标签: unsafe

关于是否使用不安全代码和stackalloc固定的困惑

我在下面有一段代码,只有一行注释掉了.该CreateArray方法中发生的情况与注释掉的行相同.我的问题是,当行b->ArrayItems = d被取消注释时它为什么会起作用,但在注释掉时会返回垃圾?我不认为我必须"修复"任何东西,因为所有的信息都是不受管理的.这个假设是不正确的?

class Program
{
    unsafe static void Main(string[] args)
    {
        someInstance* b = stackalloc someInstance[1];
        someInstance* d = stackalloc someInstance[8];

        b->CreateArray();
//      b->ArrayItems = d;

        *(b->ArrayItems)++ = new someInstance() { IntConstant = 5 };
        *(b->ArrayItems)++ = new someInstance() { IntConstant = 6 }; 

        Console.WriteLine((b)->ArrayItems->IntConstant);
        Console.WriteLine(((b)->ArrayItems - 1)->IntConstant);
        Console.WriteLine(((b)->ArrayItems - 2)->IntConstant);
        Console.Read();
    }
}

public unsafe struct someInstance
{
    public someInstance* ArrayItems;
    public int IntConstant;
    public void CreateArray()
    {
        someInstance* d = stackalloc someInstance[8];
        ArrayItems …
Run Code Online (Sandbox Code Playgroud)

c# arrays types unsafe

3
推荐指数
1
解决办法
1348
查看次数

如何在基于web的asp.net应用程序中添加unsafe关键字c#

您好我如何在基于Web的应用程序中使用不安全的关键字指针?在windows应用程序中我们在构建标签下设置项目的属性部分我们可以检查允许不安全的代码复选框,但在基于web的应用程序中如何允许不安全的代码或任何其他代替不安全的代码(指针)asp.net c#

谢谢.

asp.net unsafe

3
推荐指数
1
解决办法
4803
查看次数

将intPtr添加到int会在.net framework 3.5上生成错误

我有这个代码:

lvItem.pszText = (IntPtr)(lpRemoteBuffer + Marshal.SizeOf(typeof(LV_ITEM)));
Run Code Online (Sandbox Code Playgroud)

它在4.0上工作正常.

如果我将项目降级到3.5,它会给我这个错误:

Operator '+' cannot be applied to operands of type 'System.IntPtr' and 'int'
Run Code Online (Sandbox Code Playgroud)

任何想法如何解决这个问题,让它在3.5上工作

我不知道为什么它在4.0中有效?

提前致谢

c# unsafe unmanaged

3
推荐指数
1
解决办法
2022
查看次数

转换'编译时'类型的最快方法是什么?

我知道标题有点模糊.但我想要实现的是这样的:

在抽象类中:

public abstract bool TryGet<T>(string input, out T output) where T : struct;
Run Code Online (Sandbox Code Playgroud)

在具有此签名的类中:

private class Param<T> : AbstractParam where T : struct
Run Code Online (Sandbox Code Playgroud)

这个实现:

public override bool TryGetVal<TOriginal>(string input, out TOriginal output)
{
    T oTemp;
    bool res = _func(input, out oTemp); // _func is the actual function
                                        // that retrieves the value.
    output = (TOriginal)oTemp; // Compile-time error
    return res;
}
Run Code Online (Sandbox Code Playgroud)

而且TOriginal将永远是相同的类型T.这会绕过编译时错误,但我不想这样做会导致性能下降:

output = (TOriginal)(object)oTemp;
Run Code Online (Sandbox Code Playgroud)

如果它是引用类型,这将提供解决方案:

output = oTemp as TOriginal;
Run Code Online (Sandbox Code Playgroud)

反射/动态也可以解决问题,但性能影响更大:

output = …
Run Code Online (Sandbox Code Playgroud)

c# performance casting unsafe

3
推荐指数
1
解决办法
285
查看次数

如何将Char []或String转换为Char*以在C#中初始化SecureString?

我正在尝试初始化SecureString,我需要Char*.我尝试使用不安全的代码块:

unsafe {
    char[] c = { 'A', 'B', 'C', 'D' };
    char* pointer = &(c[0]);
    SecureString sec = new SecureString(pointer, 4);
}
Run Code Online (Sandbox Code Playgroud)

试试这个时我得到了这个错误:

错误:您只能在固定语句初始化程序中获取未固定表达式的地址

c# pointers unsafe

3
推荐指数
1
解决办法
2195
查看次数

尝试在不安全的代码中捕获异常

我正在编写一些图像处理代码并使用C#进行低级像素操作.每隔一段时间就会发生一次accessViolationException.

有几种解决这个典型问题的方法,有些认为代码应该是健壮编写的,以便没有访问冲突异常,并且据我尝试,应用程序正常但是我想添加一个try catch,以便iff的东西是要发生这种情况,应用程序不会以太丑陋的方式失败.

到目前为止,我已经提供了一些示例代码来测试它

unsafe
{
    byte* imageIn = (byte*)img.ImageData.ToPointer();
    int inWidthStep = img.WidthStep;
    int height = img.Height;
    int width = img.Width;
    imageIn[height * inWidthStep + width * 1000] = 100; // make it go wrong
}
Run Code Online (Sandbox Code Playgroud)

当我试着抓住这个陈述时,我仍然得到一个例外.有没有办法捕获不安全块中生成的异常?

编辑:如下所述,除非通过将此属性添加到函数并添加"using System.Runtime.ExceptionServices"来显式启用它们,否则不再处理此类型的异常.

[HandleProcessCorruptedStateExceptions]
    public void makeItCrash(IplImage img)
    {
        try
        {
            unsafe
            {
                byte* imageIn = (byte*)img.ImageData.ToPointer();
                int inWidthStep = img.WidthStep;
                int height = img.Height;
                int width = img.Width;
                imageIn[height * inWidthStep + width * 1000] = 100; // to make it crash …
Run Code Online (Sandbox Code Playgroud)

c# unsafe image-processing try-catch

3
推荐指数
1
解决办法
2905
查看次数

不能在C#中为变量使用关键字'fixed'

fixed用数组和字符串变量测试了关键字并且工作得非常好,但我不能使用单个变量.

static void Main() {

    int value = 12345;
    unsafe {
        fixed (int* pValue = &value) { // problem here
            *pValue = 54321;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

该行fixed (int* pValue = &value)导致编译器错误.我没有得到它,因为变量value不在unsafe块中而且还没有固定.

为什么我不能fixed用于变量value

c# pointers unsafe fixed

3
推荐指数
1
解决办法
1724
查看次数

使用C#中的索引器访问"this"指针/引用

我正在为我们的代码库中的性能/内存关键部分试验数据结构.我想快速访问结构中定义的字节.但是我不知道如何使用索引器访问我正在操作的结构.

[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Foo
{
    [SerializeField]
    private byte a, b, c;

    public unsafe byte this[byte index]
    {
        get
        {       
            //omitted safety checks   

            //this is a no, no
            byte* addr = (byte*)&this;

            return addr[index];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

c# unsafe indexer this unsafe-pointers

3
推荐指数
1
解决办法
85
查看次数

将字节数组复制到通用类型而不用拳击

我正在开发一个C#类,其中我需要能够接受一个字节数组并将其复制到相同大小的通用变量.在C/C++中,这样的事情(复制)会很容易,但在C#中并没有那么多.

MyClass<T>
{
  public T Value = default(T);

  public MyClass(byte[] bytes)
  {
    // how to copy `bytes` into `Value`?
  }
}
Run Code Online (Sandbox Code Playgroud)

我宁愿不使用拳击.有没有办法使用编组,反射或非托管/不安全代码?


我确实找到了这个其他帖子,但唯一建议的答案是行不通的,因为它使用拳击.

c# generics unsafe marshalling

3
推荐指数
1
解决办法
82
查看次数

使用分配的字符串创建Rust字符串是否安全?

我正在使用返回malloced字符串的C API :

char *foo(int arg);
Run Code Online (Sandbox Code Playgroud)

是否可以在Rust代码中重复使用该内存而不进行O(n)复制?

let p: *mut libc::c_char = foo(42);
let len = strlen(p);
let s: String = String.from_raw_parts(p, len, len);
Run Code Online (Sandbox Code Playgroud)

该文件说

所需的内存ptr必须事先由标准库使用的同一分配器分配。

我找不到标准库使用的分配器。

string unsafe rust

3
推荐指数
1
解决办法
100
查看次数