Unity3D Unsafe code requires the `unsafe' command line option to be specified - c#

i am using Unity3D 4.3 and calling a DLL that i created.
when trying to call the only function it have which is this:
void GetModelReferences(int &nVertices, float * vertices, int &nTriangles, int * triangles, float * normals, float * uvCoordinates);
unity gives me an error:
Unsafe code requires the `unsafe' command line option to be specified
so in my MonoDevelop i opened : Project->Assembly-Csharp options and turned on the unsafe mode.
it reduces part of the errors but this last one wont go away
Unsafe code requires the `unsafe' command line option to be specified
what shoud i do?

Go to your project properties page and check under Build the checkbox Allow unsafe code.
This should solve your problem.

Here is what worked for me with Unity3D 5.3:
- If in your Unity Build Setting->Player Setting->Other Settings, "API Compatibility Level" is ".Net 2.0", create a file under your Unity Asset folder called gmcs.rsp, add this following line to the file:
-unsafe
Close Unity and open it again.
- If the "API Compatibility Level" is ".Net 2.0 Subset", the above file name should be: smcs.rsp.
See the picture bellow to find the location of ""API Compatibility Level" setting in Unity.

The answer is given here: http://answers.unity3d.com/questions/804103/how-to-enable-unsafe-and-use-pointers.html
You need to add a file "smcs.rsp" (or "gmcs.rsp") in your "Assets" directory, which contains the line:
-unsafe

Have you tried this ?
look at the fifth comment
Firstly show the contents of Unity.App and drill down to Contents/Frameworks/MonoCompiler.framework.
Open the file called compile_any.pl and in the section "# Run the
csharp compiler" change #Base_Args options as below:
my #base_args=($mono_path, $mcs_path, '-debug', '-unsafe', '-target:library', '-nowarn:0169', '-out:'.$output, );

You can change the settings through the MonoDevelop:
go to the solution files tree ->
Solution -> your expand your solution -> Assempely-CSharp -> Right Click -> options -> Build -> General -> Language options -> enable "Allow 'unsafe' code"

If you're in a unity project, open Project Settings>Other Settings>Allow Unsafe Code

Related

VS Code doesn't recognise "using UnityEngine" as a valid namespace. What can I do?

I opened the ".cs" file from Unity after creating a C# file in my project, however
neither UnityEngine nor (obviously) MonoBehaviour is detected in VS Code.Due to this, Intellisense also can't help, which is a major obsticle for me, because I am completely new to the UnityEngine library. The OmniSharp log also gives a
warning in the output:
[fail]: OmniSharp.MSBuild.ProjectManager
Attempted to update project that is not loaded: c:\Users\bomka\My project\Assembly-CSharp.csproj
[warn]: OmniSharp.Roslyn.CSharp.Services.InlayHints.InlayHintService
Inlay hints requested for document not in workspace Location { FileName = c:\Users\bomka\My project\Assets\scripts\Circle.cs, Range = Range { Start = Point { Line = 0, Column = 0 }, End = Point { Line = 19, Column = 0 } } }
Things I've tried so far:
I've redownloaded both Unity and VS Code (latest versions, which are 2021.3.3f1 and 1.67.2, respectively)
I checked whether Visual Studio Code Editor and Visual Studio Editor were downloaded in Unity's Package Library (they are, it's 1.2.5 and and 2.0.15, respectively)
I changed omnisharp.path to "latest" in VS Code because I've read it resolved the "Attempted to update project..." issue. It didn't really do anything unfortunately
Does anyone have any ideas concerning what I should do here? Another useful piece of information is that this is my first ever Unity Project and so VS Code didn't just decide to malfunction after a while, this is how it's been behaving since I started writing my first piece of code for my project.
Cheers!
Is VS set in your external tools in Unity?
Edit > Pref > External Tools > External (Script) Editor : Visual Studio..
Not sure if it'll help but I know the above will fix Intellisense issues so it might be worth a shot.

Current solution contains incorrect configurations mapping using Premake5 with C#

I'm trying to develop an engine and I was looking for a GUI library in C# in order to build the editor for my engine. I found Avalonia but I'm having some problems setting up the whole environment.
I'm using Premake5 as build tool mixing C++ and C# but I think the problem here is not the languages mixing.
I'm getting this error when I generate my visual studio solution file. Sorry about the image, I needed to post it that way cause when I press the "Open Configuration Manager" the error is gone and exit the Configuration Manager window the compilation works as expected, quite weird.
Here's my code:
This is the premake5 script I run:
include "Dependencies.lua"
workspace "LeafEngine"
startproject "LeafEditor"
configurations { "Debug", "Release" }
platforms { "x64" }
flags { "MultiProcessorCompile" }
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.platform}"
group "Dependencies"
include "Leaf/vendor/glfw"
include "Leaf/vendor/imgui"
group ""
include "Leaf"
include "LeafEditor"
include "LeafGame"
Leaf is my C++ engine and LeafGame just a C++ test. Leaf editor is the C# project, which looks like this:
project "LeafEditor"
kind "WindowedApp"
language "C#"
clr "On"
targetdir ("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}")
objdir ("%{wks.location}/bin-obj/" .. outputdir .. "/%{prj.name}")
dotnetframework "net6.0"
nuget { "Avalonia:0.10.13", "Avalonia.Desktop:0.10.13",
"Avalonia.Diagnostics:0.10.13", "Avalonia.ReactiveUI:0.10.13",
"XamlNameReferenceGenerator:1.3.4"
}
files
{
"src/**.cs",
"src/**.xaml",
"src/**.xaml.cs",
}
links
{
"Microsoft.CodeAnalysis.CSharp.NetAnalyzers",
"Microsoft.CodeAnalysis.NetAnalyzers",
"System.Text.Json.SourceGeneration",
"Microsoft.NETCore.APP",
}
filter "system:Windows"
defines "LF_WINDOWS"
filter "system:Unix"
defines "LF_LINUX"
filter "configurations:Debug"
defines "LF_DEBUG"
runtime "Debug"
symbols "on"
filter "configurations:Release"
defines "LF_RELEASE"
runtime "Release"
optimize "full"
Another curious thing about Avalonia: as you can see I only have one available platform ("x64") for building. Well, Avalonia compiles with ("Any CPU") platform and that also breaks my whole building set up. Besides, Avalonia gets compiled with Any CPU when I load the project not when I compile the project, is that right?
Thanks in advance, this error is killling me.
I just had the same issue, both when my C# project was built with premake and with it as an external project.
The solution (granted I gave up on premake for C# so this may only apply to externalproject) is to not add architecture or any specific platform to your workspace, and instead add it to all but your C# project. I would leave a comment since this might not be the answer you're looking for, but I don't have enough reputation. Anyway, for example,
workspace "Lotus"
startproject "LotusEditor"
configurations
{
"Debug",
"Release"
}
project "CppProject"
architecture "x86_64" -- sets CppProject as x64 but not the workspace
-- more project config
externalproject "CsProject" -- no architecture/platform set for this. Might work for non externalprojects too
location "path"
uuid "insert uuid"
kind "WindowedApp"
language "C#"
Even with my project made manually not with premake, and set with target platform as x64, it still seems to want "Any CPU" as the configuration, which premake can't do.

MonoGame - Error 9009 & IgnoreMe.dll not found

i've just installed MonoGame and XNA and i'm having some issues from the jump, from googling it seems as though i need to add 'C:\Windows\System32' to my path environment variables, i've tried adding it here
but i'm still getting these errors
Error 1
The command "SETX MONOGAME_PLATFORM "PSM" > NUL" exited with code 9009. MyMonoGameContent
Error 2
Metadata file 'C:\Users\Benji\documents\visual studio 2013\Projects\myMonoGame\MyMonoGameContent\MyMonoGameContent\bin\PSM\IgnoreMe.dll' could not be found C:\Users\Benji\documents\visual studio 2013\Projects\myMonoGame\myMonoGame\CSC myMonoGame
This happens when i try to compile after referencing my content project
i'm following these http://rbwhitaker.wikidot.com/monogame-tutorials
no idea what's up, was that the wrong place to set the enviroment variable? i've tried looking for a user property sheet but can't find one in my project
I wouldn't expect that you would want to create content for the PSM (PlayStation Mobile). Check the targeted platform of the ContentBuilder project to ensure you are building for Windows.

Cannot obtain value because it has been optimized away

I have a problem with debugging...
All of a sudden I can't see the values of most variables while debugging.
I've managed to get two different messages in the Immediate Window:
Cannot obtain value of local or argument 'parameter' as it is not available at this instruction pointer, possibly because it has been optimized away.
and
Internal error in the expression evaluator.
I've tried and checked the following things:
Solution Configuration is set to debug (not release)
Project -> Settings -> Build -> Optimize code is not set
Tools -> Options -> Debugging -> Use Managaed Compatibility Mode (didn't work)
Do you have any further ideas how I can properly debug again? :(
Thanks in advance
Edit
The code is nothing special.. it happens when I try to watch what's inside parameter[Key]
public void AddOrUpdateQuartzJob(string jobName, IList<KeyValuePair<string, string>> parameters)
{
var jobDetail = this.GetJobDetail(jobName);
if (jobDetail != null)
{
foreach (var parameter in parameters)
{
jobDetail.JobDataMap[parameter.Key] = parameter.Value;
}
}
else
{
this.ScheduleNewJob(jobName, parameters);
}
}
The best way I've found to convince the JIT compiler not to optimize the code is to use an INI file with the name of the assembly in the same folder the assembly is in with the contents:
[.NET Framework Debugging Control]
GenerateTrackingInfo=1
AllowOptimize=0
Note that it has to be the name of the assembly, not the name of the process EXE (unless it is the EXE assembly you want to debug). E.g. if you have an assembly MyCode.dll the INI file name would be MyCode.ini.
Here are some slides from a presentation on .Net debugging which show the difference:
With Optimization:
Without Optimization:
Go to -> Project Properties -> under Build -> set "Optimize Code" checkbox Unchecked.
Also,
Under Project Properties -> Build -> Advanced -> set the "Debug Info" dropdown to "Full" in the Options
For anyone else who was stumped on this, you may be making the same simple mistake I was: my build mode was set to Release from another project I had to build for release earlier in the day. Flip it back to Debug; problem solved.
After making the changes listed by codekaizen and isanka thalagala, do not forget to clean, rebuild and publish to make the changes effective.

Powershell, Service Bus For Windows Server Programmatically: Command found, module could not be loaded

From C# code I'm trying to retrieve all the namespaces from powershell... (Later more complex things, like creating namespaces)
PowerShell ps = PowerShell.Create();
ps.AddCommand("Import-Module").AddArgument("ServiceBus").Invoke();
var result = ps.AddCommand("Get-SBNamespace").Invoke();
Above code gives the following exception:
The 'Get-SBNamespace' command was found in the module 'ServiceBus',
but the module could not be loaded. For more information, run
'Import-Module ServiceBus'.
Does anyone know how to solve this error?
CURRENT STATUS: after some debugging I've found that no modules are loaded by default in the PowerShell object. Using the code:
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(new string[]{#"serviceBus"});
PowerShell ps = PowerShell.Create(iss);
doesn't work to load the service bus module. Also the code:
ps.AddCommand("Import-Module").AddParameter("-Name", "serviceBus").Invoke();
doesn't work to import the service bus module. Running Visual Studio in administrator mode also doesn't make a difference
Thanks in advance
You didn't say which version of Visual Studio you're using. If it's VS 2012, when you tried the x64 platform target did you make sure that "Prefer 32-bit" was not checked? Even if it was not checked try checking it, saving the project configuration, clearing it and saving again - this worked for me on another project.
UPDATE
It's been suggested elsewhere that there's a bug in VS2012 that shows "Prefer 32-bit" as greyed-out and unchecked when it's actually active. I'm running Update 2 and I don't see that. But it sounds like you might be. I suggest you edit the .csproj file directly.
Whilst "Platform Target" is set at "Any CPU", in Solution Explorer, right-click on the Project name (or, with go to the PROJECT menu) and select "Unload Project". Project files will close and Solution Explorer will display project name (unavailable) > The project file was unloaded:
Right-click on the Project name again and select "Edit project name.csproj". The file is XML and mostly comprises PropertyGroup and ItemGroup elements. In a console project, the first PropertyGroup usually contains a Platform element which should read AnyCPU if you followed my instructions above. The next two PropertyGroups are normally for Debug and Release configurations. If you've added another configuration, it will have its own PropertyGroup. In each of these, look for an element which reads:
<Prefer32Bit>true</Prefer32Bit>
What you should have is an element which reads:
<Prefer32Bit>false</Prefer32Bit>
Either change it or insert it (in each configuration ProjectGroup), save the file and close it. Back in Solution Explorer, right-click the project and select "Reload Project". Let me know if that solves it. You can confirm your PowerShell is now running 64-bit by get the result of
[System.IntPtr]::Size
e.g.
ps.AddScript("[System.IntPtr]::Size");
which will be 4 in an x86 process and 8 in an x64 process.
Which my project set up like this, I was able to load ServiceBus using:
ps.AddCommand("Import-Module").AddArgument("ServiceBus");
Hopefully, you will, too.
I don't have ServiceBus installed so I can't verify exactly what you've tried but
ps.AddCommand("Import-Module").AddArgument("ActiveDirectory").Invoke();
worked for me, so your original syntax looks good.
Just to test for failure, I tried:
ps.AddCommand("Import-Module").AddArgument("CheeseDirectory");
ps.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
var importResult = ps.Invoke();
foreach (PSObject result in importResult)
{
Console.WriteLine(result);
}
and got
The specified module 'CheeseDirectory' was not loaded because no valid
module file was found in any module directory.
Have you tried similar?
Do you take care of your Assembly target in your C# program (x86 versus X64). The module may exist in one target, not in the other. PowerShell exists in both.
Seems you're trying to import some modules and execute the cmdlet or function inside the module, right?
So I think you could try the following code:
PowerShell ps = PowerShell.Create();
Assembly ass = Assembly.LoadFile(#"yourServiceBus.dll");
ps.AddCommand("Import-Module").AddParameter("Assembly", ass).Invoke();
var result = ps.AddCommand("Get-SBNamespace").Invoke();
Hope this could help.

Categories