I'm getting a strange error when I use F# to read a public readonly member of a struct type defined in a C# assembly.
// C#: compile to Lib.dll
namespace Lib
{
public class MyClass { public readonly int ReadonlyFoo; }
public struct MyStruct
{
public readonly int ReadonlyFoo;
public int WriteableFoo;
}
}
// F#: compile to Client.exe
open Lib
let myClass = new MyClass()
printfn "MyClass.ReadonlyFoo = %x" myClass.ReadonlyFoo
let myStruct = new MyStruct()
printfn "MyStruct.WriteableFoo = %x" myStruct.WriteableFoo
printfn "MyStruct.ReadonlyFoo = %x" myStruct.ReadonlyFoo
When I compile Client.exe with F# 1.9.6.16, the last line gives the error:
"The address of the variable 'copyOfStruct' may not be used at this point"
The web is useless as of the time of this writing. It seems odd that one can read an immutable member of a class, and one can read a mutable member of a struct, but one can't read an immutable member of a struct. A workaround is easy enough, but I'm curious: is this a bug in the compiler?
Edit: I submitted a bug report to fsbugs#microsoft.com
Normally when people say 'it looks like a bug in the compiler' that is code for 'I don't know what I'm doing'. In this situation however, it does look to be like a bug.
The F# compiler makes a copy of structs behind the scenes in case they get mutated. (This is why even if you define a struct with mutable fields you must attribute the instance of that struct as mutable before you can update its fields.) It appears that the special magic going on behind the scenes forgets about 'readonly' struct fields.
While the internet and StackOverflow are a great place to ask for help about F#-related issues, please do let the F# team know about any bugs you find by emailing fsbugs#microsoft.com.
Related
I am trying to get this example translated from C# to F#
public class MyModule : NancyModule
{
private IMyDependency _dependency;
public MyModule(IMyDependency dependency)
{
_dependency = dependency;
Get["/"] = x =>
{
};
// Register other routes
}
}
(source 1)
However adding a parameter to constructor
type HelloModule(dependency) as self =
inherit NancyModule()
do
self.Get.["/"] <- fun _ -> "Hello" :> obj
(source 2)
results in a run-time exception: System.InvalidOperationException: 'Something went wrong when trying to satisfy one of the dependencies during composition ...
How can I correctly add a dependency like a data-source to the code? Or, generally, how do I pass something from outside of HelloModule to the inside?
I'm guessing this might be caused by not specifying the type of the dependency parameter of the constructor in your F# code. This would result in the F# compiler assigning that parameter a generic type, and then Nancy's dependency injection framework doesn't know what to inject.
Try the following and see if it fixes your problem:
type HelloModule(dependency : IMyDependency) as self =
inherit NancyModule()
do
self.Get.["/"] <- fun _ -> "Hello" :> obj
P.S. Naturally, for this to work, you'll also need to have some type that implements the IMyDependency interface, and have told the Nancy framework about that type. From this part of the Nancy documentation that you linked to, it looks like merely declaring the type is enough, but if that's not actually enough then you'll have to register the type manually. I'm not familiar enough with Nancy to give you specific advice there beyond what the documentation says.
I have the following C# method:
private static bool IsLink(string shortcutFilename)
{
var pathOnly = Path.GetDirectoryName(shortcutFilename);
var filenameOnly = Path.GetFileName(shortcutFilename);
var shell = new Shell32.Shell();
var folder = shell.NameSpace(pathOnly);
var folderItem = folder.ParseName(filenameOnly);
return folderItem != null && folderItem.IsLink;
}
I have tried converting this to F# as:
let private isLink filename =
let pathOnly = Path.GetDirectoryName(filename)
let filenameOnly = Path.GetFileName(filename)
let shell = new Shell32.Shell()
let folder = shell.NameSpace(pathOnly)
let folderItem = folder.ParseName(filenameOnly)
folderItem <> null && folderItem.IsLink
It however reports an error for the let shell = new Shell32.Shell() line, saying that new cannot be used on interface types.
Have I just made a silly syntactic mistake, or is there extra work needed to access COM from F#?
I don't know enough about the F# compiler but your comments makes it obvious enough. The C# and VB.NET compilers have a fair amount of explicit support for COM built-in. Note that your statement uses the new operator on an interface type, Shell32.Shell in the interop library looks like this:
[ComImport]
[Guid("286E6F1B-7113-4355-9562-96B7E9D64C54")]
[CoClass(typeof(ShellClass))]
public interface Shell : IShellDispatch6 {}
IShellDispatch6 is the real interface type, you can also see the IShellDispatch through IShellDispatch5 interfaces. That's versioning across the past 20 years at work, COM interface definitions are immutable since changing them almost always causes an undiagnosable hard crash at runtime.
The [CoClass] attribute is the important one for this story, that's what the C# compiler goes looking for you use new on a [ComImport] interface type. Tells it to create the object by creating an instance of Shell32.ShellClass instance and obtain the Shell interface. What the F# compiler doesn't do.
ShellClass is a fake class, it is auto-generated by the type library importer. COM never exposes concrete classes, it uses a hyper-pure interface-based programming paradigm. Objects are always created by an object factory, CoCreateInstance() is the workhorse for that. Itself a convenience function, the real work is done by the universal IClassFactory interface, hyper-pure style. Every COM coclass implements its CreateInstance() method.
The type library importer makes ShellClass look like this:
[ComImport]
[TypeLibType(TypeLibTypeFlags.FCanCreate)]
[ClassInterface(ClassInterfaceType.None)]
[Guid("13709620-C279-11CE-A49E-444553540000")]
public class ShellClass : IShellDispatch6, Shell {
// Methods
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime), DispId(0x60040000)]
public virtual extern void AddToRecent([In, MarshalAs(UnmanagedType.Struct)] object varFile, [In, Optional, MarshalAs(UnmanagedType.BStr)] string bstrCategory);
// Etc, many more methods...
}
Lots of fire and movement, none of it should ever be used. The only thing that really matters is the [Guid] attribute, that provides the CLSID that CoCreateInstance() needs. It also needs the IID, the [Guid] of the interface, provided by the interface declaration.
So the workaround in F# is to create the Shell32.ShellClass object, just like the C# compiler does implicitly. While technically you can keep the reference in a ShellClass variable, you should strongly favor the interface type instead. The COM way, the pure way, it avoids this kind of problem. Ultimately it is the CLR that gets the job done, it recognizes the [ClassInterface] attribute on the ShellClass class declaration in its new operator implementation. The more explicit way in .NET is to use Type.GetTypeFromCLSID() and Activator.CreateInstance(), handy when you only have the Guid of the coclass.
I'm trying to study swift access control. I have came up with the code below
private class Random{}
class Person {
public var name: String = "John"
public var aRandom = Random()
}
When I declared public var name: String = "John", it only displayed an warning, saying Declaring a public var for an internal class.
When I declared public var aRandom = Random(), along with the warning, Xcode also displayed an error saying: Property must be declared private because its type "Random" uses a private type. . I was just wondering why does Xcode treat those two statements differently, where first only display an warning and second display an warning + an error?
“A public variable cannot be defined as having an internal or private type, because the type might not be available everywhere that the public variable is used.”
Excerpt From: Apple Inc. “The Swift Programming Language (Swift 2.2 Prerelease).” iBooks. https://itun.es/us/k5SW7.l
Private is meant to hide details or dependencies so that they can be changed in the future without effecting the user of that code. Being marked private, Random is only visible to code in that one file. That contradicts your intent to make a variable of that type public and visible outside the module or framework.
The reason why name does not also have an error is because its type is String which is a public type provided by the Swift standard library. It is globally available to all Swift code.
Here is code in log.h file :
struct SUCC_CODE{
static const int RECOGNIZER_OK = 0;
};
The above piece of code in log.h file throwing compiler error:
Type name does not allow storage class to be specified
Struct members may not be static. Remove that specifier, and the compiler should stop complaining. This question explains that it is a valid specifier in C++.
C doesn’t allow you to use static within a struct. It’s not even clear what that would mean in a C struct.
I'm testing a bit redis using .Net, I've read this tutorial
http://www.d80.co.uk/post/2011/05/12/Redis-Tutorial-with-ServiceStackRedis.aspx
and follow using c# and worked perfect, now when I'm trying translate this to f# I've a weird behavior, first I create a simple f# class (using type didn't work neither but it was expected)...basicaly the class is something like this:
//I ve used [<Class>] to
type Video (id : int, title : string , image : string , url : string) =
member this.Id = id
member this.Title = title
member this.Image = image
member this.Url = url
when I run the code, my db save an empty data, if I use a c# class inside my f# code this work, so I'm sure than the problem is the f# class...How can resolve this without depend c# code inside my f# code
Thanks !!!
Based on your tutorial, it looks like you want your F# Video class to be full of getter and setter properties instead of having a constructor with getters only as it is now (and it is a class, which you can verify by running it through FSI).
You can achieve this using a record type full of mutable fields (which is compiled down to a class type full of public getters and setters):
type Video = {
mutable Id : int
mutable Title : string
mutable Image : byte[]
mutable Url : string
}