I cannot import malloc/malloc.h to use malloc_size() to see the size of an object. Is it available in Swift or am I doing it wrong: import malloc/malloc.h
The Unix/POSIX stuff is all in the Darwin module.
import Darwin
let r = rand()
qsort_b(buffer, 0, 10, sortFunc)
malloc is in there, too, but it won't do you much good — it returns an opaque pointer.
Have you looked into using a bridging header?
Create a .h file named -Bridging-Header-File.h
Then reference it in your projects build settings (under "Swift Compiler" look for "Objective C Bridging Header") with:
$(SRCROOT)/<Your-Project-Name>-Bridging-Header.h
Now malloc_size() should be available
You can't import C headers. In order to import a C Library (or Objective-C framework) in Swift it has to be in a module. I'm not aware of a module that contains malloc though.
You want to use "malloc_size"? You do not need to import "malloc.h" to do that, assuming you're either including Foundation or Cocoa.
This works just fine in a playground:
import Foundation
let chars = BytePtr.alloc( 1000 )
let qty_of_bytes_allocated = malloc_size( chars )
println( qty_of_bytes_allocated )
Related
I imported math.
import 'dart:math';
But how can I call "PI" constant?
This is not working.
math.pi / 12.0
you should
import 'dart:math' as math; instead of just import 'dart:math';
because when you use the as keyword you provide the imported library a name so you can reference it anywhere in your file
As an alternative to the accepted answer, you can keep importing without a prefix, and reference pi as just pi:
import "dart:math" show pi;
main() {
print(pi / 12);
}
This works just as well as prefixing. It's a matter of taste which one you prefer.
First import 'dart:math';
then use pi/12.0 instead of math.PI/12.0 it should work fine.
The library I try to link with is:
pod 'Socket.IO-Client-Swift'
but when I try to import this in Bridging-Header like this:
#import Socket.IO-Client-Swift;
I get following error:
Expected ; after module name
Module Socket not found
Any idea how can I do this to make it working?
As I commented, it should be #import SocketIO instead of #import Socket.IO-Client-Swift;
But how/why? The imported pod is 'Socket.IO-Client-Swift' but not 'SocketIO' so what is the logic behind that?
Well, actually the Socket.IO-Client-Swift is the name of the repository (pod) but NOT the module name.
Although there is a SocketIOClient.swift file in the source directory of the socket.io-client-swift (and it DOES contains SocketIOClient file/class that you should directly work with to create a socket), but you are not importing it directly; It's similar to the case of: when you want to use Date struct -for example-, you should import Foundation.
Side-bar note:
Do you know that this is a legal (valid) code:
let date = Foundation.Date()
but because Foundation is implicitly imported, this is what we -usually- do:
let date = Date()
It is the same for all frameworks, for example the UIKit:
let view = UIKit.UIView()
:)
End side-bar.
So, what are you importing (SocketIO) is the name of the module that contains the all needed files -including SocketIOClient.swift- to let it work as it should, it appears in its Package.swift file:
let package = Package(
name: "SocketIO" )
the name of the package is SocketIO.
Another example:
Alamofire: the name of the repository is Alamofire. Also, the name of the package is Alamofire! again you can see its Package.swift:
let package = Package(
name: "Alamofire",
exclude: ["Tests"])
So, the name of the repository and its package name are identical, that's why you do import Alamofire and use it as Alamofire.request("https://httpbin.org/get").
Really hope it helped.
When trying to import JAVA modules I receive an error:
// JAVA imports
import lang::java::jdt::Java;
import lang::java::jdt::JDT;
import lang::java::jdt::JavaADT;
Could not load lang::java::jdt::Java
In the console:
rascal>import lang::java::jdt::Java;
|prompt:///|(0,29,<1,0>,<1,29>): Could not import module lang::java::jdt::Java: can not find in search path
Advice: |http://tutor.rascal-mpl.org/Errors/Static/ModuleImport/ModuleImport.html|
I'm using Eclipse and am trying to use the AstNode datatype. Any ideas?
The JDT modules have been replaced a while back by the m3 model.
While they are a bit different, the AST part should be comparable.
Check the m3 ast documentation and the Measuring java recipe.
Is this an old project you are trying to get up and running?
I'd like to be able to inflate/deflate Swift3 Data structs. I found GzipSwift, but it's not clear how I make that available to my iOS app. The naive things I've tried include:
Copying the Data+Gzip.swift file into my own project. This then complains about the import zlib at the top of said file. I think that has something to do the with the modulemap files in the zlib directory of the same sources. But I'm not sure what or how to recreate those in my own project.
Cloned the repository from github, opened XCode and built in (pressed the run button basically). Then tried to add that as a linked library or framework to my own project. I'm pretty sure just selecting the top level directory of the repository is not what I want to do, but I didn't know what else to try.
I've found some other code out there, but it seems dated and relative to Swift2.
Swift 5 implementation using Compression.
Took me a few days to realise I had to drop the first 2 bytes of the compressed data.
Hope it can help somebody else.
import Foundation
import Compression
func decompress(_ data: Data) -> String {
let size = 8_000_000
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: size)
let result = data.subdata(in: 2 ..< data.count).withUnsafeBytes ({
let read = compression_decode_buffer(buffer, size, $0.baseAddress!.bindMemory(to: UInt8.self, capacity: 1),
data.count - 2, nil, COMPRESSION_ZLIB)
return String(decoding: Data(bytes: buffer, count:read), as: UTF8.self)
}) as String
buffer.deallocate()
return result
}
I just recently had to add that exact library and file to my project, and after a lot of troubleshooting finally got it working, so let me walk you through the steps!
Okay
1) Go to the top level directory of your project in finder, and create a new folder called Swiftzlib or whatever you want the name of the module that you will be importing to be. (What we will do is add the zlib library as a module, so think of it as importing Foundation or some such other module). To clarify, this Swiftzlib directory will end up as a child directory of the same directory that contains your *.xcodeproj and *.xcworkspace files.
2) Inside the folder you created, make two files.
include.h
module.modulemap
3) In your include.h file, enter the following:
#include<zlib.h>
4) In your module.modulemap file, enter the following:
module Swiftzlib [system] {
header "include.h"
export *
}
Where Swiftzlib is the same as the name of the folder that you created.
5) Open your Xcode project, and select your target
5a) In Build Phases -> Link Binary with Libraries, add libz.tbd
5b) In Build Settings -> Swift Compiler - Search Paths, add $(PROJECT_DIR)/Swiftzlib non-recursively to the import paths
5c) In Build Settings -> Other Linker Flags, add -lz as a flag
6) Select your project in Xcode (may not be necessary, but I've done it in my project and it works)
6a) In Build Settings -> Swift Compiler - Search Paths, add $(PROJECT_DIR)/Swiftzlib non-recursively to the import paths
7) In Data+Gzip.swfit, add import Swiftzlib to the top of the file
8) Clean, Build, and Run!
I maintain a small Swift 3+ wrapper around Apples native libcompression framework at:
https://github.com/mw99/DataCompression
Usage example for gzip:
let data: Data! = "https://www.ietf.org/rfc/rfc1952.txt".data(using: .utf8)
let gzipped: Data! = data.zip()
let gunzipped: Data? = gzipped.unzip()
assert(data == gunzipped)
But if you are only interested in classic inflate and deflate you may use the .inflate() and .deflate() methods instead. That will save 18 bytes because the gzip header won't be added.
I made a small spm extension inspired by #vauxhall 's answer
https://github.com/mezhevikin/Zlib
import Zlib
// Decompressed data
print(data.decompressed)
// Decompressed string
print(data.decompressedString)
I know you can use the library, import and even #import, but which is correct?
I have got two files, MainClass.dart and Library.Dart, and I want to add a reference to Library.dart in MainClass.dart. How can I do that?
Firstly let me just preface this by saying please do not use the hash symbol before import or library or anything else. This is an old syntax that is being deprecated. So we no longer want to use #import('...') The correct syntax is:
import 'some_file.dart';
That said, there are two different things we can do to access different dart source files within our current file. The first is to import the file. We use this such as in your case when you want to bring a different library into the current file (or more accurately current library).
Usually if your files are in the same directory, or a sub directory of the current one we would import them like this:
import 'lib/library.dart';
However If you are using the pub package layout you can also use some special short-cut references as well to import files (particularly from other packages you've imported). I highly suggest reading the documents on the pub site, as most applications and libraries are designed with this in mind. It also has suggestions on best naming conventions such as filenames in all lower case, and using underscore for spaces, and directory layouts.
The other important thing to know about bringing a dart file into another file, is that we can use the part and part of directives. This used to be called #source but was changed (with the removal of the hash sign) to reduce confusion. The part directive is used when we want to write a single library which spans multiple files. Say for instance you have an Awesome Library, which is starting to get a little large for a single file. We will create the main file of the library (not to be confused with the main method). This file will usually have the same name as the library itself.
// awesome_library.dart
library awesome_library;
import 'dart:math';
import '...';
// this injects all the content of secret_file.dart
// into this file right here almost as if it was
// here in the first place.
part 'src/secret_file.dart';
// The rest of our file here
// ...
The part directive basically takes everything from our src/secret_file.dart and inserts it into that part of the file. This allows us to split our huge Awesome Library into multiple smaller files that are easier to maintain. While not specifically required, it is helpful to use the part of directive in our secret_file.dart to help the editor know that it is "part of" the library.
// secret_file.dart
part of awesome_library;
// ... Rest of our secret_file code below.
Note that when using a part file like this, the part(s) (that is everything that is not the main file of the library) cannot import or use library declarations themselves. They import whatever is imported into the the main file, but they cannot add any additional imports.
For more information about library see this link.
Importing your own created libraries:
You will be importing the filename.dart and not the name of your library.
So if the name of your library is: myLib and it is saved in the file: someDartFile.dart you will have to
import 'someDartFile.dart';
If you have on Windows a library at: K:\SomeDir\someFile.dart you will need to write:
import '/K:/SomeDir/someFile.dart';
example:
import 'LibraryFile.dart'; //importing myLib
void main(){
//a class from myLib in the LibraryFile.dart file
var some = new SomeClassFromMyLibrary();
}
myLib in LibraryFile.dart:
library myLibrary;
import 'dart:math';
class SomeClassFromMyLibrary{
String _str = "this is some private String only to myLibrary";
String pubStr = "created instances of this class can access";
}
Here a full example.
//TestLib.dart
import 'LibFile.dart'; //SomeLibrary
void main() {
print("Hello, World!");
LibFile l = new LibFile();
print(l.publicString);//public
print(l.getPrivateString);//private
print(l.getMagicNumber); //42
}
//LibFile.dart
library SomeLibrary;
part 'LibFile2.dart';
class LibFile {
String _privateString = "private";
String publicString = "public";
String get getPrivateString => _privateString;
int get getMagicNumber => new LibFile2().number;
}
//LibFile2.dart
part of SomeLibrary;
class LibFile2 {
int number = 42;
}
Although i am answering very late, but the answer may help new developer.
Always use pubspec.yaml file in your dart package(application/library).
once you run pub get command it will add your local library in the dependencies list in .packages file.
Consider i have following project structure.
To refer to the content of greeting.dart in my main.dart file i should add the library as below
import 'package:my_project_name/greeting.dart'
Once imported we can use the content of greeting.dart file in our main.dart file.
Note: we have not used the actual path as you can see 'lib' directory is missing.
First make sure that's the name which you have mentioned in pubspec.yaml and the file you want to import are sharing the exact same name
example:
pubspec.yaml
name: flutter_wordpress_app
description: flutter wordpress app
...
....
// dirOne/dirTwo/greeting.dart
class FavArticleBloc {
// Your code goes here
}
import 'package:flutter_wordpress_app/dirOne/dirTwo/greeting.dart'
void main(){
var some = new FavArticleBloc();
}
But
in the main.dartyou don't need to specify
import 'package:flutter_wordpress_app
just do like below
import 'dirOne/dirTwo/greeting.dart