oleg-shilo / cs-script

C# scripting platform
http://www.cs-script.net
MIT License
1.56k stars 234 forks source link

DllImport how to use in script #363

Open ghost opened 5 months ago

ghost commented 5 months ago

How can i use DllImport attribute like below? When try to use it the compiler trows an type loading error

[DllImport("user32.dll")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

Error: InvalidCastException unable to cast object of type 'Mono.CSharp.ImportedTypeDefinition' to type 'Mono.CSharp.MemberCore'

oleg-shilo commented 5 months ago

I am not sure what version of the script engine you are using and what is the hosting platform. IE the current version of CS-Script has no dependency on Mono.

Anyway, the simple answer is "Exactly as with any C# code". image

ghost commented 5 months ago

So I was on an older version of CS Script, after version 3.29.0 the script runs, but when using CS-Script.bin to load the code it now is throwing the following error:

FileNotFoundException: The file or assembly 'Microsoft.CodeAnalysis.Scripting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies could not be loaded. The system was unable to locate the specified file.

ghost commented 5 months ago

I've changed the EvaluatorEngine to be CodeDom and it now works without problem, can't be sure why... My Project compiles a DLL that then is inject to a third party program, maybe this affects what AppDomain is used to add the references?

ghost commented 5 months ago

If some one has the same problem and want to use newer c# syntax this is how i solve it

CSScript.EvaluatorConfig.Engine = EvaluatorEngine.CodeDom;
                    CSScript.GlobalSettings.UseAlternativeCompiler = "PATH TO DLL\CSSRoslynProvider.dll";
                    CSScript.GlobalSettings.RoslynDir = "PATH TO Package\Microsoft.Net.Compilers.2.2.0\tools";

execute the following to get the DLL and the Microsoft Net Compilers -> Install-Package CS-Script.RoslynProvider

oleg-shilo commented 5 months ago

And if you prefer to use Roslyn then you need to add Microsoft.CodeAnalysis.Scripting packages. The current CS-Script does it automatically but the old one needed the user to do it manually.